Rails AJAX - getting a dropdown selection to popul

2019-01-24 22:34发布

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.

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?

Dropdown (with AJAX call):

<%= collection_select :id, Project.all, :id, :name, :onchange => remote_function(:url=>{:action => 'populate_projects'}) %>

Controller action:

 def populate_projects
    @project = Project.find(params[:id])
 end

And the existing table:

<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 => "&pound;") %></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>

3条回答
时光不老,我们不散
2楼-- · 2019-01-24 22:52

Assume you're using jquery

<%= collection_select :project, :id, Project.all, :id, :name, {}, {:onchange => '$.get("/populate_projects")'} %>

then in your controller

def populate_projects
  @project = Project.find(params[:id])
  respond_to do |format|
    ...
    format.js { render 'populate_projects', :formats => [:js] }
    ...
  end
end

finally, create populate_projects.js.erb and write any change table content script. @project is available in that script.

查看更多
爷、活的狠高调
3楼-- · 2019-01-24 22:58

In js(RJS) file you need to call partial HTML file and this file have tables That you shown here in your question.

I hope this helps you.

Thanks.

查看更多
疯言疯语
4楼-- · 2019-01-24 23:10

Create one partial _project.html.erb and render this partial in index page. <%= render @projects %> On change of project just render partial with project object and update page using rjs.

查看更多
登录 后发表回答