nil_class使用partial时

时间:2012-03-30 15:38:54

标签: ruby-on-rails ruby-on-rails-2

我有以下代码:

new.html.erb

<% form_for @car,:html => {:name => 'car_form'}  do |f| %>
  <% time_created = Time.new %>
  <%= f.hidden_field :CAR_DATE_CREATED, :value => time_created %>
  <%= render :partial => "car_partial", :locals => {:object => @car } %>
  <%= f.submit 'Create'  %> 
<% end %>

_car_partial.html.erb

<% fields_for @car do |f| %>
  Origin: <%= f.select(:ORIGIN_TYPE,
            [['Origin X', 'X'],
            ['Origin Y', 'Y'],
            ['Other origin', 'Other']
            ],{:prompt => "Please select"}  
            ) %>


  <%= observe_field("car_ORIGIN_TYPE", :frequency => 2,
                      :url => { :controller => 'car',
                      :action => :display_other_origin },
                      :with => "'id='+value") %>



  <span id="otherOrigin" > </span>

<% end %>

控制器代码

def display_other_origin
    origin = params[:id]
end

display_other_origin.rjs

   if params[:id] == "Other"
      page['otherOrigin'].replace_html :partial => 'car/other_origin_type', :locals => {:car => @car }
    else
      page.replace_html :otherOrigin, ''
    end

_other_origin_type.html.erb

<% fields_for @car do |f| %>
If other, please state: <%= f.text_field :ORIGIN_TYPE, :size => 20%>
<% end %>

如果用户选择“其他来源”,则部分会正确显示,但当我执行<view source>时,

Origin: <select id="car_ORIGIN_TYPE" name="car[ORIGIN_TYPE]">
        <option value="X">Origin X</option>
        <option value="Y">Origin Y</option>x
        <option value="Other">Other origin</option>
        </select>

<script type="text/javascript">
//<![CDATA[
new Form.Element.Observer('car_ORIGIN_TYPE', 2, function(element, value) {new Ajax.Request('/cars/display_other_origin', {asynchronous:true, evalScripts:true, parameters:'id='+value + '&authenticity_token=' + encodeURIComponent('+MtiIQj/KfX2huaetD1E7W7f2pu/HC2d31BhCPjcmlQ=')})})
//]]>
</script>

<span id="otherOrigin">
If other, please state: <input id="nil_class_ORIGIN_TYPE" name="nil_class[ORIGIN_TYPE]" size="20" type="text">
</span>

显示nil_class而不是'car'。

任何帮助???

由于

1 个答案:

答案 0 :(得分:0)

您的控制器操作display_other_origin未设置@car变量 - 因此在display_other_origin.rjs文件中使用时为nil。

基本上,在observe_field方法中,您还需要为car id设置一个参数。例如:

<%= observe_field("car_ORIGIN_TYPE", :frequency => 2,
                  :url => { :controller => 'car',
                  :action => :display_other_origin },
                  :with => "'id='+value+'&car_id='#{@car.id}") %>

然后您可以在@car = Car.find(param[:car_id])

中执行display_other_origin

...虽然我应该注意,约定规定params [:id] - 传递给CarsController时 - 应该是car id,你的起源应该是params [:origin]