Greetings, I’m looking for suggestions on how to simplify getting
customer
addresses on a form:
I’m jumping between controller and view several times; alternating
between
rhtml and rjs, in order to display customers and their addresses on an
invoicing form. It’s very messy.
I have a one to many relationship between Customer and Addresses, each
customer has one or more addresses. The user opens the Invoice form and
selects from a list of customers which in turn populates and displays a
list
of that customer’s addresses.
It works like this:
- The Invoice controller receives a new request and renders the
new.rhtmlform:
/invoices/new
def new
@invoice = Invoice.new
@customers = Customer.find(:all, :order => “name”)
end
new.rhtml
<% form_for :invoice, @invoice, :url => { :action => “create” } do |f|
%>
Customer:
<%=
collection_select(:invoice, :customer_id, @customers, :id,
:name,
{:include_blank => true},
{:onchange => remote_function(:url => { :action =>
“get_customer”},
:with => “‘invoice_customer_id=’+
$F(‘invoice_customer_id’)”)}
)
%>
<%= hidden_field :invoice, :customer_id, :value => “” %>
<%= submit_tag ‘Add Invoice’ %>
<% end %>
- The onchange event calls the controller action get_customer, which
does a
find on the selected customer_id. It also gets the address collection
and
then Rails renders the customer.rjs which in turn inserts customer.rhtml
/invoices/get_customer/1
def get_customer
@customer = Customer.find(params[:invoice_customer_id])
@addresses = Customer.find(params[:invoice_customer_id]).addresses
end
customer.rjs
page[:customer].replace_html :partial => ‘customers/customer’, :object
=>
@customer
page[:customer].visual_effect :highlight
customer.rhtml
<%=
collection_select(:invoice, :address_id, @addresses, :id,
:street,
{:include_blank => true},
{
:onchange => remote_function(:url => { :action =>
“get_address”},
:with => “‘invoice_address_id=’+ $F(‘invoice_address_id’)”)
})
%>
- Next a similar pattern occurs for addresses…
Back we go to the controller with the action get_address and then render
address.rjs and then address.rhtml. It’s annoying because I have other
values to gather on this form that also have multiple joins.
I suspect the culprit of this complexity is the onchange event and
remote_function calls. I’ve considered calling a local javascript
function
to expose the selected customer’s addresses – they are available via
the
@customer object thanks to the has_many relationship — however, I
haven’t
figured out how to do that.
Possibly a entirely different solution exists. Your thoughts and ideas
are
gratefully appreciated!
–Dave