[英]Check for nested attributes in before_save
當您向控制器提交表單以保存在ActiveRecord中時,可以通過@foo.field = 'bar'
添加缺少的字段。 我想對嵌套屬性做同樣的事情,但是我不知道怎么做。
我正在嘗試做類似的事情:
'@foo.bar.field = 'baz'
foo模型
accepts_nested_attributes_for :bar
如果那更有意義。
編輯:相關的模型代碼
class Product < ActiveRecord::Base
...
has_many :update
belongs_to :user, :foreign_key => 'user_id'
accepts_nested_attributes_for :update, :reject_if => lambda {|a| a[:body].blank?}
...
end
更新型號
class Update < ActiveRecord::Base
...
belongs_to :product, :foreign_key => 'product_id'
geocoded_by :address
reverse_geocoded_by :latitude, :longitude
validates :body, :presence => true
end
((params[:product])["update_attributes"])["0"].merge!({"user_id" => u_id})
ed,但解決了
@foo.bar.field = 'baz'
與accepts_nested_attributes_for
無關。 您可以將before_save
驗證添加到Bar
模型中,然后可以完美地與以下代碼一起使用:
bar = @foo.bar
bar.field = "baz"
bar.save
# => now before_save will be executed
通過accepts_nested_attributes_for
它看起來像這樣:
@foo.bar_attributes = { :id => XXX, :field => "baz" }
@foo.save
在這種情況下,您應該將驗證添加到Foo
模型中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.