【问题标题】:ActiveRecord accepts_nested_attributes and callbacksActiveRecord 接受_nested_attributes 和回调
【发布时间】:2012-12-06 23:48:09
【问题描述】:

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 中获取它们。一定有更好的方法来做到这一点?

【问题讨论】:

  • 你得到的错误究竟是什么?您的方法(检查before_create 中的关系)只是感觉错误。
  • 另外,如果将set_disabled 的回调更改为after_create,是否会出现同样的错误(无论它是什么)?您需要再次致电模型上的save,但我很好奇。
  • 我没有尝试使用after_create。所有这些都需要一起保存。全有或全无。错误是它不能调用nilClass 没有方法namepost.authors 在这一点上是一个空白数组,所以这是有道理的。

标签: ruby-on-rails activerecord ruby-on-rails-3.2


【解决方案1】:

我不确定你是否会从另一边获得更好的运气(我目前无法测试这个),但是从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

【讨论】:

    【解决方案2】:

    您的模型只需稍作改动。只需在关联后添加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
    

    【讨论】:

    • 我没有意识到顺序很重要。但是我的实际代码实际上在关联之后有accepts_nested_attributes_forattr_accesssible 声明在中间。我将对其进行编辑并回复您。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    相关资源
    最近更新 更多