我有三个模型Post
:Replies
和User
。Reply
sa 的嵌套资源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
如何用回复填充一定数量的帖子?