Ajax在多个模型的Rails中形成部分

时间:2010-07-29 04:49:35

标签: ruby-on-rails ajax jquery partials

我有很多视图中存在的 AJAX代码(来自:http://badpopcorn.com/blog/2008/09/11/rails-observer-field/)(主要是new.html.erb和edit.html.erb)。为了避免代码重复,我假装使用partials:

应用/视图/城市/ _state_city_form.html.erb

<p> State:
  <%= select(:state, :state_name, City.all(:select => 'DISTINCT(state)', :order => :state).collect {|c| [ c.state.titleize, c.state ] }, {:include_blank => true})%>
  <%= observe_field 'state_state_name', :url => { :action => :by_state,
                                                  :controller => :cities },
                                                  :update => 'cities_list',
                                                  :with => "'state='+ $('#state_state_name').val()" %>
</p> City:
  <div id="cities_list">
    <%= select(modelname.to_sym, :city_id, [], {:include_blank => true})%>
  </div>
<p>
</p>

我也有Ajax回调内容:

应用/视图/城市/ by_state.html.erb

<%= select(/*PROBLEM_HERE*/, :city_id, @cities.collect {|c| [ c.name, c.id ] }, {:include_blank => true})%>

我的城市控制员:

应用/控制器/ cities_controller.rb

class CitiesController < ApplicationController

  def by_state
    @cities = City.find_all_by_state(params[:state])
    render :layout => false
  end

end

然后我只需要在每个需要的地方调用部分:

应用/视图/用户/ new.html.erb

...
<%= render :partial => 'cities/state_city_form', :locals => { :modelname => :user } %>
...

应用/视图/雇员/ new.html.erb

...
<%= render :partial => 'cities/state_city_form', :locals => { :modelname => :employee } %>
...

在这里,我可以将用户:employee 传递给partial,但是如何将它们传递给Ajax回调?

1 个答案:

答案 0 :(得分:0)

您可以尝试将模型名称作为字符串传递给partial,并使用to_sym将其转换为符号。

希望这有帮助。