0

我有三个模型PostRepliesUserReplysa 的嵌套资源Post

回复.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

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

4

2 回答 2

1

为什么不直接make_reply在. 也许你可以有一些条件来决定有多少回复,或者其他什么,但它本质上是一样的。关键是需要保存父级(帖子)才能拥有一个 id。但这几乎正是您的创建控制器方法所做的,对吧?50.timesmake_posts

所以像

def make_posts
  users = User.all(limit: 6)
  50.times do
    title = Faker::Lorem.sentence(1)
    content = Faker::Lorem.sentence(5)
    users.each do |user| 
      user.posts.create!(title: title, content: content)
      # 1 post is now saved, get it, then make reply
      post = user.posts.first  # maybe you already have this as a return from create?
      make_reply(post)
    end
  end
end

def make_reply(post)
  # find a random user to be the replier
  replier = User.find method_that_returns_random_user
  content = Faker::Lorem.sentence(10)  # or whatever
  post.replies.create!(user: replier.id, content: content)
end

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

于 2012-11-20T00:52:52.907 回答
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
于 2012-11-20T05:22:29.707 回答