Marko Anastasov wrote this on February 25, 2009

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 nestedthing’s attributes? For example, we don’t want to display the filefield, since leaving it blank would make Paperclip think that the associated attachment should be deleted, but render a link to the attachment instead.

fieldsfor “creates a scope around a specific model object like formfor” doc, and one of the attributes that you can access is called objectname. Say we’re in an edit action’s view. objectname then is a string which looks like main_model[nestedthingattributes][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

About Marko Anastasov

Rendered Text co-founder. Started with code, currently more focused on people and words. Foosball striker and entry-level cyclist.

Suggested Reads

Rails Testing Handbook

A new ebook on building test-driven Rails apps with RSpec and Cucumber.

At Rendered Text, we have a long history with Ruby on Rails. Checking the blog archive reminds me that we published first posts about working with Rails way back in 2009.

———

Rendered Text is a software company. For questions regarding Semaphore, please visit semaphoreci.com. Otherwise, feel free to get in touch any time by sending us an email.