Rails动态搜索模型

时间:2017-08-01 15:43:31

标签: jquery ruby-on-rails ruby ruby-on-rails-4

我有以下型号:

拥有:型号 car_brand_id 字段的汽车。 CarBrand只有一个:名称字段和has_many:汽车

在视图中,我有一个带有搜索结果的搜索表单,如下所示:

<%= search_form_for(@q, url: search_result_path) do |f| %>

  <%= f.select(:year_eq, 1960..(Date.today.year+1), {prompt: 'year'}, class: "grey-text") %>
  <%= f.collection_select :car_brand_id_eq, CarBrand.all, :id, :name, {prompt: 'brand'}, class: "grey-text" %>
  <%= f.collection_select :model_eq, Car.models, :model, :model, {prompt: 'model'}, class: "grey-text " %>
  <%= f.button "Search" %>

<% end %>

我想使表单搜索动态化,例如,如果用户在表单中选择特定年份,则下一个字段(:car_brand_id)仅返回选择的选项,这些选项具有之前选择的年份,依此类推与下一个字段。提前谢谢。

1 个答案:

答案 0 :(得分:0)

我对这样的问题有特殊的关注,因为我花了很长时间才弄清楚类似的事情。所以一般来说应该是这样的:

  1. 使用实例变量设置<%= f.collection_select :car_brand_eq, CarBrand.all... collection_select,您可以根据ajax调用和可以引用它的类来更新该实例变量。变化:

    <%= f.collection_select :car_brand_eq, @car_brands, :id, :name, {prompt: 'brand'}, class: "grey-text car-brand-collection" %>
    

    到:

    <%= f.select(:year_eq...
  2. 设置您的AJAX呼叫:

    获取要在jquery中使用的<%= f.select(:year_eq, 1960..(Date.today.year+1), {prompt: 'year'}, class: "grey-text year-selector") %> 的id或为其添加唯一的类名:

    <script>
      $(document).on("change", ".year-selector", function () {
        $.ajax({
          url: "/car_brands/search.js",
          // now pass params[:year] as a query string
          data: { year: $(".year-selector").val() },
          type: "GET"
        });
      });
    </script>
    

    然后是剧本:

    search_car_brands_path
  3. 现在设置car_brands_controller.rb路由,然后设置resources :car_brands do collection do # search_car_brands_path get :search end end 中的逻辑,或者您将使用的其他控制器:

    routes.rb (an explantion of this routes logic here)

    ...
    # GET /car_brands/search
    # search_car_brands_path
    def search
      # not knowing how exactly you filter CarBrands by year, I'm guessing:
      @car_brands = CarBrand.where(year: params[:year])
    end
    

    <强> car_brands_controller.rb

    // grab that car-brand-collection selector from step 1 & update it
    $(".car-brand-collection").html("<%= f.collection_select :car_brand_eq, @car_brands, :id, :name, {prompt: 'brand'}, class: "grey-text car-brand-collection" %>");
    
  4. 最后。现在你只需要在:

    中设置search.js.erb

    <强>视图/ car_brands / search.js.erb

    position: relative
  5. 这些是步骤。我没有对它们进行过测试,但你应该能够从这里开始研究它。