Tuesday 20 October 2009

Haven't given up

Just been working on another project.
Complex forms - you have to love them.
Had a problem with having a form updating more than one model - in this case it has to update an address as well.
Devil's own business getting the drop down menu to work - and then found Ryan Bates' comment - I want to marry him ...

Here is the partial to be rendered
<% new_or_existing = address.new_record? ? 'new' : 'existing' %>
<% prefix = "organisation[#{new_or_existing}_address_attributes][]" %>
<% fields_for prefix, address do |address_form| %>

<%= address_form.error_messages %>


<%= address_form.label :address_1 %> <%= address_form.text_field :address_1 %>



<%= address_form.label :address_2 %> <%= address_form.text_field :address_2 %>



<%= address_form.label :address_3 %> <%= address_form.text_field :address_3 %>



<%= address_form.label :town_city %> <%= address_form.text_field :town_city %>



<%= address_form.label :county_state %> <%= address_form.text_field :county_state %>



<%= address_form.label :postcode_zip %> <%= address_form.text_field :postcode_zip %>



<%= address_form.label :country %> <%= address_form.text_field :country %>



<%= address_form.label :live %> <%= address_form.select :live, [['No', false], ['Yes', true]]%>


<% if new_or_existing == 'new' %>


<%=address_form.label :address_type_id %> <%= address_form.collection_select(:address_type_id, AddressType.find_all_by_live(true), :id, :name, {:index=>""}) %>


<% end %>
<% end %>


Then the model is as follows:
def new_address_attributes=(address_attributes)
#handles the address edit form in the edit view
address_attributes.each do |attributes|
addresses.build(attributes)
end
end

def existing_address_attributes=(address_attributes)
addresses.reject(&:new_record?).each do |address|
attributes = address_attributes[address.id.to_s]
if attributes
address.attributes = attributes
else
addresses.delete(address)
end
end
end

def save_addresses
addresses.each do |address|
address.save(false)
end
end


And there is a callback to save the address in the case of an update

after_update :save_addresses

Getting the address_type collection to work was an absolute bugger - it kept rejecting the
organisation[new_address_attributes][]
saying it wasn't allowed. That was when I found Ryan's comment about using the same fields_for thingy and yay - it all works.

No comments:

Post a Comment