简体   繁体   English

使用下拉列表和带有Rails的AJAX填充表单字段

[英]Populate form fields using a dropdown and AJAX with Rails

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: 在我的new.html.erb视图中:

<%= 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: 在populate_contact_form.rjs中:

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

It seems my controller method is never called... can anyone explain how to do this? 似乎从未调用过我的控制器方法...谁能解释如何做到这一点?

It's not getting called because you're using remote_function incorrectly. 之所以没有被调用是因为您使用的remote_function不正确。 Rails assumes the current action/controller/id/etc if any of those options are missing from the :url option to remote_function. 如果从remote_function的:url选项中缺少任何这些选项,Rails会假定当前为action / controller / id / etc。 You're passing :action as a top level option to remote_function, and it gets ignored. 您将:action作为顶级选项传递给remote_function,它将被忽略。 With a :url option Rails assumes the same action and controller that rendered this view. 使用:url选项,Rails假定呈现此视图的动作和控制器相同。

This should fix your problem: 这应该可以解决您的问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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