I have Shop has_many :documents and Documen belongs_to :shop. When I create a new shop I use accept_nested_attributes_for :documents in the model and fields_for in the form, so I can create a new shop and at the same time a document associated to the shop. I want to add a new document associated to the shop also when I edit the shop, at the same time I edit the shop. If I call the edit action for shop, in the form I have the fields for one of the documents associated with their values but I want to add a new document. There is a way to do this?
Checkout these two railscasts, they should get you started in right direction:
http://railscasts.com/episodes/196-nested-model-form-part-1
http://railscasts.com/episodes/197-nested-model-form-part-2
Chirag http://sumeruonrails.com
I've found that is more simpler than I've thought.
Models are:
Shop has_many :document, Document belongs_to :shop.
For edit action I've done:
@shop = Shop.find(params[:id]) @document = @shop.documents.new
and in the form I've done:
fields_for @document.
Now I can modify an existing shop and at the same time add a document. Do you think it's all correct?
I’m assuming this is rails 3.
For your edit action you don’t need the @document variable. You can refer to all of your documents via the :has_many association you created in the model so @shop.documents will suffice.
Your fields_for will need to look something like this
fields_for :documents, @shop.documents |ff_item|
stuff for whatever you need (text area’s checkboxes etc.)
end
If you want to access your data from your document in the fields_for loop, you can do “ff_item.object.DOCUMENT_METHOD”.
ff_item.object will be an instance of your document so you can set the default values for your html items.
Vinny
@agnellvj
The problem is that I want to add a new document when I am in the edit action. In the form for edit I have all shop fields with their values and also the document fields with their values. I want the document fields blank so that I can insert new values and add a document for the shop.