Mauro
(Mauro)
February 3, 2011, 4:52pm
1
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?
[http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html](http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html)
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 %>
Mauro
(Mauro)
February 4, 2011, 4:29pm
3
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.