2

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>
4

3 に答える 3

4

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そのスクリプトで使用できます。

于 2012-07-04T11:48:12.120 に答える
0

1つのパーシャルを作成_project.html.erbし、このパーシャルをインデックスページにレンダリングします。 <%= render @projects %> プロジェクトの変更時に、プロジェクトオブジェクトで部分的にレンダリングし、rjsを使用してページを更新します。

于 2012-07-04T10:49:09.243 に答える
0

js(RJS) ファイルでは、部分的な HTML ファイルを呼び出す必要があり、このファイルには、質問でここに示したテーブルがあります。

これがお役に立てば幸いです。

ありがとう。

于 2012-07-04T10:51:38.920 に答える