开发者

Rails - advanced search

I was able to accomplish a standard search in one of my models using AJAX:

VIEW:

<%= form_tag facilities_path, :method => 'get', :id => "facilities_search", :remote => true do %>
    <%= text_field_tag :search, params[:search], :placeholder => 'Find facility', :class =&g开发者_开发技巧t; "search" %>
    <%= submit_tag "Search", :name => nil %>
<% end %> 

MODEL:

 def self.search(search)
   if search
     where(['lower(name) LIKE ?', "%#{search.downcase}%"])
   else
     scoped
   end
 end

index.js.erb:

$("#facilities").html("<%= escape_javascript(render("facilities")) %>");

application.js:

  $("#facilities_search input").keyup(function() {
    $.get($("#facilities_search").attr("action"), $("#facilities_search").serialize(), null, "script");
    return false;
  });

Now i would like to build an "advanced search", and in particular i would like to put 3 radio buttons above the search (A, B, C) field to allow the user tho choose the model to search. In other words if he select B, the search will be within Bs.

How can I do that?


I think you have a couple of options to choose from to determine how to implement this.

Option 1: You could use JavaScript onclick functions on the radio buttons to change the submit target for the form (the form action). So, depending on which radio button (target model) is selected, you could have the form submit to different controllers based on where the search should be run.

Option 2: Another option, which would probably be cleaner and less subject to user-issues (i.e. if the user has JavaScript disabled), would be to route all searches to one controller method and then call different models based on the value of the parameters:

def search
    @results = []

    # if the user selects the "user" radio button
    if params[:searchtarget] == "user"
        @results = User.search(params[:term])
    # order radio button selected
    elsif  params[:searchtarget] == "order"
        @results = Order.search(params[:term])
    # default
    else
        @results = Notes.search(params[:term])
    end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜