Rails AJAX - 获取下拉菜单来填充表格 [英] Rails AJAX - getting a dropdown selection to populate a table
问题描述
我正在尝试从下拉列表中选择在同一页面中使用AJAX来填充表格,以便更改显示,而不刷新页面。我已经制定了远程调用的代码,并将自定义操作添加到控制器,但是我不知道如何将返回的信息存入表中。目前,表格正在循环遍历所有项目,但我希望它仅显示所选择的一个项目的信息。
I'm trying to get a selection from a dropdown to populate a table in the same page, using AJAX so that changes appear without a page refresh. I've got as far as working out the code for the remote call, and adding the custom action to the controller, but I don't know how to get the returned information into the table I've got. At the moment, the table is just looping through all the projects, but I want it to only display the info for the one project that is selected.
我需要什么写一个JS(rjs?)文件来获取它来处理返回的信息,以及需要对现有表进行什么更改以确保显示正确的信息?
What would I need to write in a JS (rjs?) file to get it to process the returned information, and what changes would I need to make to the existing table to make sure that it is displaying the correct info?
下拉(使用AJAX调用):
Dropdown (with AJAX call):
<%= collection_select :id, Project.all, :id, :name, :onchange => remote_function(:url=>{:action => 'populate_projects'}) %>
控制器操作:
def populate_projects
@project = Project.find(params[:id])
end
现有表:
<table>
<tr>
<th>Name</th>
<th>Category</th>
<th>Budget</th>
<th>Deadline</th>
<th>Company ID</th>
<th></th>
<th></th>
<th></th>
</tr>
<% @projects.each do |project| %>
<tr>
<td><%= project.name %></td>
<td><%= project.category %></td>
<td><%= number_to_currency(project.budget, :unit => "£") %></td>
<td><%= project.deadline.strftime("%A, %d %B %Y") %></td>
<td><%= project.company_id %></td>
<td><%= link_to 'More', project %></td>
<td><%= link_to 'Edit', edit_project_path(project) %></td>
<td><%= link_to 'Delete', project, confirm: 'Are you sure?', method: :delete %></td>
</tr>
<% end %>
</table>
推荐答案
假设你使用jquery
Assume you're using jquery
<%= collection_select :project, :id, Project.all, :id, :name, {}, {:onchange => '$.get("/populate_projects")'} %>
然后在您的控制器中
def populate_projects
@project = Project.find(params[:id])
respond_to do |format|
...
format.js { render 'populate_projects', :formats => [:js] }
...
end
end
最后,创建 populate_projects.js.erb
并写任何更改表内容脚本。 @project
在该脚本中可用。
finally, create populate_projects.js.erb
and write any change table content script. @project
is available in that script.
这篇关于Rails AJAX - 获取下拉菜单来填充表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!