One form for one model with nested resources

I have:

Customer
has_many :deliveries
has_one :document

Document
belongs_to :customer

Delivery
belongs_to :customer

route.rb has:

resources :customers do
resources :deliveries
end

I already have customers in the database, I only have to add
deliveries and document to one customer.
I want to do with one single form.
Obviously this one doesn’t work:

<%= form_for([@customer, @delivery]) do |f| %>
<%= f.input :delivered_at, :as => :hidden, :value => Date.today %>
<%= f.fields_for :document do |doc| %>
<%= doc.label :doc_type %>
<%= doc.text_field :doc_type %>
<%= doc.error :doc_type %>
<% end %>
<%= f.submit %>

It adds deliveries but not document.

Some advices?

Haven’t tested it, but perhaps you try something like this:

class Customer
has_many :deliveries
has_one :document

accepts_nested_attributes_for :deliveries, :reject_if => lamda {
|attributes| attributes[‘delivered_at’].blank?}
accepts_nested_attributes_for :document

end

<%= form_for(@customer) do |f| %>
<%= f.fields_for :deliveries, @delivery do |delivery_fields %>
<%= delivery_fields.input :delivered_at, :as => :hidden, :value =>
Date.today %>
<% end %>
<%= f.fields_for :document do |doc_fields| %>
<%= doc_fields.label :doc_type %>
<%= doc_fields.text_field :doc_type %>
<%= doc_fields.error :doc_type %>
<% end %>
<%= f.submit %>
<% end %>

On 03/02/11 17:52, Mauro wrote:

belongs_to :customer
I want to do with one single form.

It adds deliveries but not document.

Some advices?


best regards
Bente P.

On 4 February 2011 16:07, Bente P. [email protected]
wrote:

accepts_nested_attributes_for :document
<%= doc_fields.text_field :doc_type %>
<%= doc_fields.error :doc_type %>
<% end %>
<%= f.submit %>
<% end %>

I’ve solved in this manner:

<%= form_for([@customer, @delivery]) do |f| %>
<%= f.input :delivered_at, :as => :hidden, :value => Date.today %>
<%= fields_for @document do |doc| %>
<%= doc.label :doc_type %>
<%= doc.text_field :doc_type %>
<% end %>
<%= f.submit %>

I’ve used fields_for and not f.fields_for.
I’ve seen that there’s no need to use accept_nested_attributes.