0

クラス

class Post < ActiveRecord::Base
  accepts_nested_attributes_for :comments
  accepts_nested_attributes_for :authors
  has_many :comments
  has_many :authors
end

class Author < ActiveRecord::Base
  belongs_to :post
end

class Comment < ActiveRecord::Base
  attr_accessible :disabled
  belongs_to :post
  before_create :set_disabled

  def set_disabled
    if self.post.authors.first.name == "Foo"
      self.disabled == true
    end
  end
end

ネストされた属性を使用して新しい投稿を作成する

params = {
  post: {
    title: "A New Post", 
    comments_attributes: [
      { body: "This is a great post" }
    ], 
    authors_attributes: [
      {name: "Foo"}
    ]
  }
}

a = Post.create(params)

set_disabledメモリ内にあるにもかかわらず、コメントが にアクセスできないため、コールバックでエラーが発生しpost.authorsます。

現在の解決策は、 からそれらを取得することですObjectSpace。これを行うためのより良い方法があるはずですか?

4

2 に答える 2

0

モデルを少し変更するだけで済みます。関連の後にnested_attributesを追加するだけです

class Post < ActiveRecord::Base
  has_many :comments
  has_many :authors
  accepts_nested_attributes_for :comments
  accepts_nested_attributes_for :authors

  attr_accessible :comments_attributes, :authors_attributes, :title .....

end
于 2012-12-07T05:03:40.000 に答える
0

反対側から運が良いかどうかはわかりませんが(現時点ではこれをテストできません)Postそれ自体からこれを試してみるのはどうですか:

class Post < ActiveRecord::Base
  # your associations ...

  before_create do
    comments.each do |c|
      c.disabled = true
    end if authors.first.name == "Foo"
  end
end
于 2012-12-07T02:12:33.717 に答える