如何根据参数使用where子句

时间:2016-01-16 13:41:31

标签: ruby-on-rails

我试图让用户能够输入他们可以从数据库中过滤的多个字段。现在,当用户选择要搜索的列时,我会动态创建输入。

表单提交网址

/sites.csv?zipcode=74656?state=newyork.

可能有多个相同的字段示例

/sites.csv?zipcode=78656?zipcode=74656?. 

我希望能够获得包含邮政编码78656和74656的所有字段,或者说明纽约和邮政编码74656.无论用户输入什么,无论发送多少字段都无关紧要。

如何获取这些参数并为每个参数执行where子句

站点控制器

class SitesController < ApplicationController
    def index
        // If parameters exist 
         // do where clause
        else
         @sites = Site.all
       respond_to do |format|
                format.html
                format.csv { send_data  // if fields exist  dont use all sites @sites.to_csv }
                format.xls 
        end
    end
    private

    def site_params
        params.require(:site).permit(:latitude, :longitude, :building_height, :zoning_class, :state, :town, :zipcode, :county, :first_name, :last_name, :company_name)
    end
end

索引页

    = form_tag("/sites.csv", method: :get) do
            #csv-modal.modal.fade{"aria-labelledby" => "myModalLabel", :role => "dialog", :tabindex => "-1"}
                .modal-dialog
                    .modal-content
                        .modal-header
                            %button.close{"aria-label" => "Close", "data-dismiss" => "modal", :type => "button"}
                                %span{"aria-hidden" => "true"} &times;
                            %h4.modal-title Download CSV
                        .modal-body
                            .btn-group
                                %button.btn.btn-default.btn-sm.dropdown-toggle{"aria-expanded" => "false", "aria-haspopup" => "true", "data-toggle" => "dropdown", :type => "button"}
                                    Add Fields
                                    %span.caret
                                %ul.dropdown-menu.csv-selector
                                    %li
                                        %a
                                            Latitude
                                    %li
                                        %a
                                            Longitude
                                    %li
                                        %a
                                            State
                                    %li
                                        %a
                                            Town
                                    %li
                                        %a
                                            Zipcode
                                    %li
                                        %a
                                            County
                                    %li
                                        %a
                                            Building Height
                                    %li
                                        %a
                                            Zoning Class
                                    %li
                                        %a
                                            First Name
                                    %li
                                        %a
                                            Last Name
                                    %li
                                        %a
                                            Company Name

                            .input_fields_wrap
                                %div
                        .modal-footer
                            %button.btn.btn-default{"data-dismiss" => "modal", :type => "button"} Close
                            %button.btn.btn-default{:type => "submit"} Download CSV

:javascript

    $(document).ready( function () {

        $('.table').DataTable();

        var max_fields = 10; //maximum input boxes allowed
        var wrapper = $(".input_fields_wrap"); //Fields wrapper
        var add_button      = $(".add_field_button"); //Add button ID

        var x = 1; //initlal text box count
        $(".csv-selector > li > a").click(function(e){ //on add input button click
            e.preventDefault();
            if(x < max_fields){ //max input box allowed
                x++; //text box increment
                $(wrapper).append('<div><input type="text" name="'+$(this).text().trim().toLowerCase()+ '" class="form-control small-field" placeholder="'+$(this).text().trim()+'"/><a href="#" class="remove-field btn btn-danger remove-field">Remove</a></div>'); //add input box
            }
        });

        $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
            e.preventDefault(); $(this).parent('div').remove(); x--;
        })
    });

2 个答案:

答案 0 :(得分:0)

当使用相同的URL参数时,Rails会合并数组中的值,并将其指定为参数哈希中参数的值。因此,对于请求/sites.csv?zipcode=78656?zipcode=74656?,参数将是:

params[:zipcode] #=> [78656, 74656]

使用where时,ActiveRecord会为值数组构建IN条件,以便您可以直接传递params哈希:

class SitesController < ApplicationController
    def index
      @sites = Site.where(params)

答案 1 :(得分:0)

您的网址请求参数需要与&分开:

/sites.csv?zipcode=74656&state=newyork.

要将这些问题传递给where查询,您必须执行以下操作:

def index
   records = []
   params.each do |k,v|
      records << k #-> ["zipcode", "state"]
   end

   @sites = Site.all
   records.uniq!.each do |param|
     @sites += @sites.where("#{param} IN ?", params[param.to_sym])
   end