0

、、の3つのモデルPostRepliesありUserます。ReplyのネストされたリソースPost

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

特定の数の投稿に返信を入力するにはどうすればよいですか?

4

2 に答える 2

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 に答える
1

のループmake_reply内でメソッドを呼び出さないのはなぜですか。おそらく、返信の数などを決定するいくつかの条件を持つことができますが、それは基本的に同じです。重要なのは、親(Post)がIDを持つためには、それが保存されている必要があるということです。しかし、これはあなたのcreatecontrollerメソッドがすでに行っていることとほぼ同じですよね?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 に答える