One-to-many nested attributes in rails
This is not a question, but hopefully someone can benefit from it.
When you try to create or modify a one-to-many nested association make sure that you're passing an array. If you're getting
NoMethodError (undefined method `[]' for...
and you're working with a one-to-many nested association this might be your problem开发者_高级运维. I didn't find an explanation for this when searching for this error so maybe this will help speed up someone else's development.
For example, I have a Person model with
has_many :person_images
accepts_nested_attributes_for :person_images
In order to create a new person and associated person_image I do the following.
@person = Person.create(:full_name=>@person_name, :person_images_attributes=>[{:image=>person_image}])
Notice the [] around {:image=>person_image}. If you have a one-to-many you must have this. So the following doesn't work and produces the undefined method '[]' error.
@person = Person.create(:full_name=>@person_name, :person_images_attributes=>{:image=>person_image})
Also, in my views I'm having to name my inputs like this
<input type="file" name="person[person_images_attributes][0][image]">
It doesn't work without the [0].
I'm new to Rails. I hope this helps other beginners and if someone has a better explanation or a more efficient way to do this I'd be grateful for your comments.
For details see Rails API on Nested Attributes
Use formtastic for creating forms, it will handle those [0] things you write about.
See here:
http://railscasts.com/episodes/184-formtastic-part-1 http://railscasts.com/episodes/185-formtastic-part-2
And If you are new to RoR those are really good sites to learn from.
http://railscasts.com http://guides.rubyonrails.org/
By the way it seems to me that you have little twisted relationships in Person model. You probably used
has_many :person_images
But you use [0] to get the first one.
精彩评论