`

AJAX级联下拉菜单 related drop-down lists

阅读更多
      在问答里看到xu_ch问一个问题,关于下拉列表的。想起,之前做过一个关于用AJAX,级联动态更新下拉菜单的类似功能。借这个机会整理出来以便有点用处。


      最初的一篇据说经典,我想翻译一下:

      http://www.roryhansen.ca/2005/06/21/related-drop-down-lists-with-ruby-and-ajax/

     一些抱怨

However, this code actually creates HTML in the controller component:

@albums = Album.find_all_by_artist_id(@params["artist_id"])
@html = ""
@html += "No Album"
@albums.each do |@album|
   @html += "#{@album.album_name}"
end
@html += ""




I would think this is considered 'bad practice', because this is the job of
the view.

How could one rewrite this and get a cleaner controller code?


<select name="yes_or_no" id="yes_or_no" >
  <option value="1">Yes</option>
  <option value="0">No</option>
</select>

<%= observe_field 'yes_or_no',
        :frequency => 1, 
        :update => 'div_to_be_updated',
        :url => {:controller => 'controller', :action=> 'action' }, 
        :with => "'is_delivery_address=' + escape(value)" %>

#in your controller
def action
  if params[:is_delivery_address] == "1"
    render :partial => 'nothing'  
  else 
    render :partial => 'address_partial'  
  end
end


 # _form.rhtml
 <%=  options_from_collection_for_select(Coordinator.find_all, "id",
 "coordinator_name") %>
 #get_projects
 def get_projects
    @results = Project.find_all
    render :partial => 'options'
 end

 # _options.rhtml
 <% for project in @results do -%>
 <%=project.project_number%>
 <% end -%>



controller里边:
def test
  @provinces = Province.find(:all)
end

def select_with_ajax
  @cities = City.find(params[:province_id])
  render :partial => "select_city"
end 


 


test.rhtml的代码:

<%= javascript_include_tag :defaults %>
<%= select(:province, :id, @provinces.map {|u| [u.name, u.id]},options = {},
  html_options = {"onchange" => remote_function(
    :with=> "'province_id='+value",                                       :update => 'city_select',
    :url => { :action => :select_with_ajax })})
%>


_select_city.rhtml的代码:

<%= select(:city, :id, @cities.map{|u| [u.name,u.id]}) %> 


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics