Master/Detail issue

Hello,

I’ve been spinning arround an issue for days and simply don’t know
how 11`to solve it in rails.
I’m sure there is a simple solution for my problems once this is a
very common situation.
Well, I have a has_many/belongs_to association in my project that
goes like this:

Farm < ActiveRecord::Base
has_many :parties, :dependent => ‘delete_all’
end

Party < ActiveRecord::Base
belongs_to :farm
end

OK, The creation and deletion of the parties goes very well,
including validations and etc. My problem is regarding to updating the
detail records. I simply didn’t get how to do it. It seems to me that
simple assignment don’t work… I think that @farm.parties= only
create new records and delete those that are no longer assigned.
My questions are:

  1. How can I update information in child records?
    For this one I did something like
    params[:farm][‘parties’].each do |p|
    p.save
    end

  2. I did the following to “pass” the errors from the detail to the
    master:
    params[:farm][‘parties’].each do |p|
    if !p.save
    @farm.errors.add_to_base(‘oh no!!’)
    end
    end
    OK, the problem is that when some error occur, when the edit action
    is rendered again, it is shown with the old values, the ones that are
    in the DB.

It is late at night and I am sorry if my explanations are not enough.

Thank you all in advance.


Ricardo A.
[email protected]
Acras Desenvolvimento de Sistemas
+55+41-3232-6404
www.acras.net

I think you want
@farm.parties << a_party
@farm.save

Ricardo A. wrote:

  1. How can I update information in child records?
    For this one I did something like
    params[:farm][‘parties’].each do |p|
    p.save
    end

In Farm model, add a :before_update callback that saves existing
parties, i.e.

parties.each {|p| p.save unless p.new_record?}

  1. I did the following to “pass” the errors from the detail to the
    master:
    params[:farm][‘parties’].each do |p|
    if !p.save
    @farm.errors.add_to_base(‘oh no!!’)
    end
    end

Try using validates_associated

Regards
Massimo
http://www.addsw.it