简体   繁体   中英

Rails 2.3.5 collection_select: how to grab attributes from selected object and send to javascript function

I have a collection_select with the following code:

    <%= collection_select(:address, :id, current_user.addresses, :id, :address1, options ={:prompt => "Select an address"}, 
        html_options={:onchange => "insert_address_fields()"}) %>

insert_address_fields gets called properly when i select an address in the list, but what i want to do is send all the attributes of of the selected address (first name, last name, address, city, state, etc) to the insert_address_fields function. Something like insert_address_fields(<% address.attributes %>) , or, if i have to, list the the attributes individually. Is this possible with the setup i have now without making things overly complicated?

collection_select generates an <input> with a set of <options> fetched from the column of the table you are setting.

You can only (and should) send the selected address to insert_address_fields() by doing "insert_address_fields(this.value)". In this case, this will be the input field of the html.

The function should take care of fetching the relevant information from the address by accessing the database.

¿Why?

  1. Otherwise, you are giving too much responsiblity to the view. The view should not parse information and send it to the function (it should be the other way around!)

  2. If you add a column to the address atributes, you will need to change your view. Adding columns should be transparent to the view of your application

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM