如何根据Rails中的表单输入动态更新搜索结果?

时间:2015-07-21 00:51:00

标签: ruby-on-rails

我希望网站访问者能够在半径内查看附近的节目,可以通过下拉表单输入。我有一个视图,使用Geocoder gem显示附近的节目:

<h3> Shows near <%= request.location.city %> </h3>
<%= form_for @nearby_shows.first do |f| %>
<p> Radius (in miles): <%= f.select(:radii, [10,20,30,40,50], {},
   :style => "width:50px", :selected => f.object.radii, :onchange =>
   "location.href = '#{shows_path}'") %> </p>
<% end %>
<ul class="users">
  <% @nearby_shows.each do |nearby_show| %>
    <li>
      <%= link_to nearby_show.show_name, nearby_show %>
    </li>
  <% end %>
</ul>

现在,选择不会影响任何内容,并且在页面刷新时不会在表单中记住选择。

模型show.rb包含:

attr_accessor :radii

节目控制器包含:

def index
    @shows = Show.all
    @radii = 50
    @nearby_venues = Venue.near("Boulder, CO",@radii,:select =>
    "id").to_a
    @nearby_shows = Show.where(show_venue: @nearby_venues)
end

在制作中,我将使用request.location.city,但在开发中我只是使用&#34; Boulder,CO&#34;举个例子。

如何使用输入选择表单设置@radii?我担心form_for不允许我更改实体列表@nearby_shows的变量。

1 个答案:

答案 0 :(得分:0)

如果你想要一个快速的AJAX解决方案,这就是我要做的事情

首先,在列表中添加一个ID,以便于操作

<ul id="my_id" class="users"></ul>

我真的不明白为什么你需要那个<%= form_for @nearby_shows.first %>?如果我理解得很好,你只想显示一个选择,并根据用户选择的内容更新附近节目的列表?

<强>的routes.rb

resource :shows do
  get 'update_nearby', on: :collection, constraints: { format: 'js' }
end
# GET /shows/update_nearby, meant to be used only with AJAX

<强> your_view.html.erb

<%= form_tag update_nearby_shows_path, remote: :true do |f| %>
<p> Radius (in miles): <%= select_tag(:radii, [10,20,30,40,50], {},
   :style => "width:50px", :selected => @radii, :onchange =>
   "location.href = '#{shows_path}'") %> </p>
<% end %>

<!-- On Submit, it will request a JS response 
     You can add some JS to submit the form everytime the select changes -->

添加一些JS特定的响应

<强> your_controller.rb

def update_nearby
  find_nearby_shows
end

private
def find_nearby_shows
  @radii = params[:radii] ? params[:radii] : 50
  @nearby_venues = Venue.near("Boulder, CO",@radii,:select =>
    "id").to_a
  @nearby_shows = Show.where(show_venue: @nearby_venues)
end

<强> update_nearby.js.erb

<% if @nearby_shows %>
  // Empty the list
  var id = $("#my_id").empty()
  <% @nearby_shows.each do %>
    // Add one <li> per show
    $("<li>", { 'html': "<%= escape_javascript(link_to(nearby_show.show_name, nearby_show)) %>"}).appendTo(id)
  <% end %>
<% end %>

奖金:你说你想保存半径?您实际上可以尝试将其添加到用户会话

def index
  ...
  @radii = session[:saved_radii] ? session[:saved_radii] : DEFAULT_RADIUS
  ...
end

def update_nearby
   find_nearby_shows
   session[:saved_radii] = @radii
end

但如果你真的想为用户保存,那么你的用户模型中应该有一个preferred_radii字段