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 -


Thanks to Mark for reminding us to update the post.

comments powered by Disqus

About Marko Anastasov

Marko co-founded Rendered Text. He’s a programmer with a passion of creating something for other people, coupled with interests in how things work in the society and nature. He is having a great time working across many areas in the company, including product design, helping the engineering teams, empowering users and marketing. He likes to counterbalance it all with running, cycling or a day in the woods.

Suggested Reads

Inject is a fundamental building block

Inject is one of the fundamental, and most versatile constructs available in functional languages. It can be used to implement map, select, max, all? and a bunch of other iteration related methods. Unfortunately, many programmers are not aware of its awesome powers. This article is here to improve this fact.


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

Rendered Text
Svetozara Miletica 10
21000 Novi Sad