使用回复填充帖子(sample_data.rake)?

时间:2012-11-20 00:33:23

标签: ruby-on-rails rake

我有三个模型:PostRepliesUserReplyPost的嵌套资源:

replies.rb:

class Reply < ActiveRecord::Base
  attr_accessible :content
  belongs_to :user
  belongs_to :post, :counter_cache => true
  .
  .
  .

发表。 RB:

class Post < ActiveRecord::Base
  include ActionView::Helpers

  attr_accessible :title, :content

  belongs_to :user

  has_many :replies, dependent: :destroy
  .
  .
  .

这就是我在sample_data.rake文件中的内容:

sample_data.rake:

def make_users
  admin = User.create!(name:     "Example User",
                       email:    "example@railstutorial.org",
                       password: "foobar",
                       password_confirmation: "foobar")
  admin.toggle!(:admin)
  99.times do |n|
    name  = Faker::Name.name
    email = "example-#{n+1}@railstutorial.org"
    password  = "password"
    User.create!(name:     name,
                 email:    email,
                 password: password,
                 password_confirmation: password)
  end
end

def make_posts
  users = User.all(limit: 6)
  50.times do
    title = Faker::Lorem.sentence(1)
    content = Faker::Lorem.sentence(5)
    users.each { |user| user.posts.create!(title: title,
                                           content: content) }
  end
end

这是我创建回复的方式:

  def create
    @post = Post.find(params[:post_id])
    @reply = @post.replies.build(params[:reply])
    @reply.user_id = current_user.id
    if @reply.save
     # do this
    else
     # do this
    end
  end

如何使用回复填充一定数量的帖子?

2 个答案:

答案 0 :(得分:1)

为什么不在make_reply的{​​{1}}循环内调用方法50.times。也许你可以有一些条件来确定有多少回复,或者其他什么,但它基本上是相同的。关键是父(Post)需要保存才能拥有id。但这几乎就是你的创建控制器方法已经完成的了,对吧?

类似

make_posts

您需要一种方法来提出有效的用户ID作为回复者。

答案 1 :(得分:1)

rand方法返回一个随机整数,直到传入的值,所以你可以这样做:

def make_reply(post)
  # So we dont query the database for the size of the users table each time
  @user_count ||= User.count
  replier = User.find(rand(@user_count))
  content = Faker::Lorem.sentence(10)  # or whatever
  post.replies.create!(user: replier.id, content: content)
end