开发者

Populate form fields using a dropdown and AJAX with Rails

开发者 https://www.devze.com 2022-12-12 20:31 出处:网络
I have a form field where a user enters contact information, including name, email, etc. If they already have contacts saved I want to have a dropdown with their saved contacts. When a contact from th

I have a form field where a user enters contact information, including name, email, etc. If they already have contacts saved I want to have a dropdown with their saved contacts. When a contact from the dropdown is selected, the contact fields should be populated with that data to allow for easy editing.

For some reason this approach isn't working:

In my new.html.erb view:

<%= f.collection_select :id, @contacts, :id, :name, :onchange =>
remote_function(:url =>{:action => 'populate_contact_form'}, :with => 'id') %>

In my controller:

def populate_contact_form
raise "I am working up to this point"
@contact = current_account.contacts.find(params[:id])
end

In populate_contact_form.rjs:

page['contact_name'].value = @contact.name
page['contact_email'].value = @contact.email

It seems my co开发者_如何学JAVAntroller method is never called... can anyone explain how to do this?


It's not getting called because you're using remote_function incorrectly. Rails assumes the current action/controller/id/etc if any of those options are missing from the :url option to remote_function. You're passing :action as a top level option to remote_function, and it gets ignored. With a :url option Rails assumes the same action and controller that rendered this view.

This should fix your problem:

<%= f.collection_select :id, @contacts, :id, :name, :onchange => 
  remote_function(:url =>{:action => 'populate_contact_form'}, :with => 'id') %>
0

精彩评论

暂无评论...
验证码 换一张
取 消