我可以使用rails控制台来识别唯一的种子数据

时间:2022-02-15 20:45:48

Not even sure if this is (a) something that can be done or (b) something I need to be concerned about. I had a project to write a seeds.rb file for seeing a RoR app with test data. My file is below:

甚至不确定这是否是(a)可以做的事情或(b)我需要关注的事情。我有一个项目要编写一个seeds.rb文件,用于查看带有测试数据的RoR应用程序。我的文件如下:

require 'random_data'

50.times do
Post.create!(
    title: RandomData.random_sentence,
    body: RandomData.random_paragraph
)
end
posts = Post.all

100.times do
Comment.create!(
    post: posts.sample,
    body: RandomData.random_paragraph
)
end

unique_post = {
title: 'unique title',
body: 'unique body'
}

unique_post_id = Post.find_or_create_by!(unique_post)

unique_comment = {
post: unique_post_id,
body: "unique comment"
}

Comment.find_or_create_by!(unique_comment)

puts "Seed finished"
puts "#{Post.count} posts created"
puts "#{Comment.count} comments created"
puts "#{unique_post.count} unique posts created"
puts "#{unique_comment.count} unique comments total"

Everything works fine. Resulting messages are:

一切正常。结果消息是:

Seed finished
251 posts created
501 comments created
2 unique posts created
2 comments total

I have two questions:

我有两个问题:

  1. Why did I end up with 2 unique posts and 2 unique comments?
  2. 为什么我最终得到2个独特的帖子和2个独特的评论?
  3. Can I use the rails console to identify those unique posts and comments?
  4. 我可以使用rails控制台来识别这些独特的帖子和评论吗?

Thanks.

谢谢。

1 个解决方案

#1


1  

The reason you are seeing 2 unique posts and comments is because you're counting the hash keys of the object attributes, not the created object(s)..

您看到2个唯一帖子和评论的原因是因为您计算对象属性的哈希键,而不是创建的对象。

{ key1: 123, key2: 456, key3: 789 }.count
=> 3

You can use Rails console to query for those unique posts/comments by just querying the table: Comment.find_by(title: 'unique title')

您可以使用Rails控制台通过查询表来查询这些独特的帖子/评论:Comment.find_by(title:'unique title')

#1


1  

The reason you are seeing 2 unique posts and comments is because you're counting the hash keys of the object attributes, not the created object(s)..

您看到2个唯一帖子和评论的原因是因为您计算对象属性的哈希键,而不是创建的对象。

{ key1: 123, key2: 456, key3: 789 }.count
=> 3

You can use Rails console to query for those unique posts/comments by just querying the table: Comment.find_by(title: 'unique title')

您可以使用Rails控制台通过查询表来查询这些独特的帖子/评论:Comment.find_by(title:'unique title')