How can I use drop down box with Ajax to render a partial in Rails?
I created drop down menu layouts as follows.
<select name="search" id="search" >
<option value="0">Please select</option>
<option value="1">Name</option>
<option value="2">Trainer</option>
<option value="3">Venue</option>
<option value="4">Date</option>
</select>
<div id="div_to_be_updated" style="float:right"></div>
<%= observe_field 'search',
:update => 'div_to_be_updated',
:url => {:controller => 'events', :action=> 'find' },
:with => "'is_delivery_address=' + escape(value)" %>
Then I created find method in my controller.
def find
if params[:is_delivery_address] == "1" || "2" || "3"
render :partial => 'layouts/new_search'
else
render :partial => 'layouts/nothing'
end
end
Then I created partial called _new_search.
<span style="text-align: right">
<% form_tag "/events/find_search" do %>
<%= text_field_tag :search_string%>
<%= submit_tag "search" %>
<%end%>
</span>
Again I created find_search method in controller.
def find_search
events=Event.find(:all, :conditions=>["venue = ?", params[:search_st开发者_Go百科ring]])
end
Then I created view page. But when I searched somehting it will give exception.
NoMethodError in Events#find_search
Showing app/views/events/find_search.html.erb where line #10 raised:
You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.each
What should I do? Can anybody help me>
Not sure if this is it - but the following line has a bug
if params[:is_delivery_address] == "1" || "2" || "3"
this will always be true, since if params[:is_delivery_address] != "1"
then the result will be "2" (non-nil - ie true).
Try irb to check:
> params = {:is_delivery_address => "0" }
> params[:is_delivery_address] == "1" || "2" || "3"
=> "2"
I have this working in Production:
<% form_for :youractionhere, :url => { :action => "youractionhere", :param1 => @market, :param2 => @param2 } do |f| %>
<%= select_tag :search, options_from_collection_for_select(@search_options, "search_option_name", :search_option_name, :search_option), { :onchange => "this.form.submit();" } %>
<% end %>
The key is to have the :url => { :action => "youractionhere"} and also the {:onchange => "this.form.submit();"} in it. The action, of course, should render the partial when called.
精彩评论