rails ransack remote with with pagination

时间:2017-07-13 12:42:10

标签: ruby-on-rails ruby ajax pagination

我有WeekDay的控制器。然后我尝试在我的项目中添加RanSack。它工作正常,除非我尝试启用remote true时,它只显示搜索表单。正在进行AJAX调用,但没有任何显示。

控制器代码

def index
  @q = WeekDay.ransack(params[:q])
  @week_days = @q.result().page(params[:page]).per(10)

  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @week_days }
  end
end

index.html.erb

<div id="week_days"><%= render 'week_days' %></div>

_week_days.html.erb

<%= search_form_for @q,remote: true do |f| %>
<%= f.label :datum_gteq %>
<%= f.date_field :datum_gteq%>
<%= f.label :datum_lteq %>
<%= f.date_field :datum_lteq %>
<%= f.submit %>
<% end %>
<table> 
<thead>
<tr>
  <th><%=sort_link @q, :datum %></th>
  <th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @week_days.each do |week_day| %>
  <tr>
    <td><%= l week_day.datum %></td>
    <td><%= link_to 'Show', week_day %></td>
    <td><%= link_to 'Edit', edit_week_day_path(week_day) %></td>

  </tr>
<% end %>
</tbody>
</table>
<%= paginate @week_days %>
<br>

<%= link_to 'New Week Day', new_week_day_path %>

1 个答案:

答案 0 :(得分:1)

我的一些想法是你将_week_days拆分为partial,然后使用ajax渲染数据的一部分,我添加了名为display-area的新div作为ajax渲染的目标,你应该创建javascripts来渲染它而不重新加载页面与逃避javascripts(j)

_week_days.html.erb

<%= render "search" %> 
<%= render "my_data" %> 

_search.html.erb

<%= search_form_for @q,remote: true do |f| %>
    <%= f.label :datum_gteq %>
    <%= f.date_field :datum_gteq%>
    <%= f.label :datum_lteq %>
    <%= f.date_field :datum_lteq %>
    <%= f.submit %>
<% end %>

_my_data.html.erb

<div class="display-area">
    <table> 
        <thead>
            <tr>
                  <th><%=sort_link @q, :datum %></th>
                  <th colspan="3"></th>
            </tr>
        </thead>
    <tbody>
    <% @week_days.each do |week_day| %>
      <tr>
        <td><%= l week_day.datum %></td>
        <td><%= link_to 'Show', week_day %></td>
        <td><%= link_to 'Edit', edit_week_day_path(week_day) %></td>

      </tr>
    <% end %>
    </tbody>
    </table>
    <%= paginate @week_days %>
    <br>
    <%= link_to 'New Week Day', new_week_day_path %>    
</div>

在app / assets / javascripts中写_weekdays.js.erb

$('.display-area').html("<%= j render(partial: 'my_data') %>")