开发者

Check for nested attributes in before_save

When you submit a form to the controller for saving in ActiveRecord, you can add missing fields via @foo.field = 'bar'. I would like to do the same thing for a nested attribute, but I cannot figure out how.

I am trying to do something like:

'@foo.bar.field = 'baz'

where the foo model

accepts_nested_attributes_for :bar

if that makes more sense.

Edit: relevant model code

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

Update model

class Update < ActiveRecor开发者_开发百科d::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})

long winded, but that solved it


@foo.bar.field = 'baz'

is not about accepts_nested_attributes_for. You can add before_save validation into Bar model and then it will perfectly work with:

bar = @foo.bar
bar.field = "baz"
bar.save
# => now before_save will be executed

Via accepts_nested_attributes_for it will looks like that:

@foo.bar_attributes = { :id => XXX, :field => "baz" }
@foo.save

In this case you should add validation into Foo model

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜