Getting model instances from form objects
What happens when you you’re using the new nested attributes feature from the upcoming Rails 2.3, with code in your view like
<% main_model_form.fields_for :nested_things do |nt_form| %># ...
and you don’t want just to render form fields for these, but to access one of the current nested_thing’s attributes? For example, we don’t want to display the file_field, since leaving it blank would make Paperclip think that the associated attachment should be deleted, but render a link to the attachment instead.
fields_for “creates a scope around a specific model object like form_for” [doc], and one of the attributes that you can access is called object_name. Say we’re in an edit action’s view. object_name then is a string which looks like main_model[nested_thing_attributes][id]. So in order to extract that id number and get the right object instance, you can do
@main_model.nested_things.find(nt_form.object_name.gsub(/\D/, '').to_i)
Update: this is all it really takes -
nt_form.object.attribute
Thanks to Mark for reminding us to update the post.
Comments powered by Disqus