Banging my head against this one for a long time. On Rails 2.3.2, Ruby 1.9.1.
Trying to use one form to create three objects that have these relations:
class Person
has_one :goat
end
class Goat
belongs_to :person
has_many :kids
end
class Goat::Kid
belongs_to :goat
end
Here's a summary of the schema:
Person
first_name
last_name
Goat
name
color
Goat::Kid
nickname
age
I'd like my #create
action to instantiate new instances of all three models with the specified associations. However, while it appears that my params hash is being passed to the controller as it should (based on the backtrace logs in the browser when it blows up), the Goat::Kid
object is not collecting the params.
irb (irb session is just a psuedo-representation of what I'm trying to accomplish so if it doesn't call #save!
or any other necessities it's not really meant to be correct. I'm trying to do this all through the browser/web form.)
a = Person.new :first_name => 'Leopold', :last_name => 'Bloom'
b = Goat.new :name => 'Billy', :color => 'white'
c = Goat::Kid.new :nickname => 'Jr.', :age => 2
a.goat.kids
>> []
Now, I cannot figure out how to get the view to pass the params to each object and to get the controller to save these params to the db.
My questions: A) is this a good place to use nested_attributes_for
and if so how do I declare that with a namespace? B) is there a much simpler, easier to understand way to do this?
Passing params to three models has just been very challenging to me and no matter how much documentation I read I can't wrap my head around it (#form_for
and #fields_for
). The namespace further complexifies this. Thanks for any help!
Addendum: if I end up declaring
accepts_nested_attributes_for
what's the proper way to use the symbol argument for a namespaced model?
accepts_nested_attributes_for :kids, :through => :goats
or
accepts_nested_attributes_for :goats_kids, :through => :goats
or
accepts_nested_attributes_for :goats::kids, :through => :goats
I'm not sure how namespaced models translate to their symbol identifiers. Thanks!