rails_for中的fields_for

时间:2012-02-22 12:03:41

标签: ruby-on-rails ruby ruby-on-rails-3

将另一个应用程序从Rails 2转换为Rails 3 - 在我的一个视图中,我有以下代码:

<%fields_for "order[commission_attributes][]", commission do |f|%>

这是由以下控制器操作驱动的:

def edit
  @order = Order.find(params[:id],:include=>[{:orderitems=>:item_schedules}, :memberids ],:order=>"orderitems.updated_at DESC")
  @active_order_iems = []
  @inactive_order_items = []
  @order.orderitems.each do |oi|
    oi_active = nil
    oi.item_schedules.each do |is|
        if (is.end_date > Date.today)
          oi_active =true
          break
        end
    end
    @active_order_iems << oi if !oi_active.nil?
    @inactive_order_items << oi if oi_active.nil?
  end

  @commissions = @order.commissions.find(:all)
  @ordertypes = Ordertype.find(:all, :order=>"description")
  @salesreps = Salesrep.find(:all, :order=>"fullname")
  @customers = Customer.find(:all, :order=>"company_name")
  @memberids = Memberid.find_all_by_customer_id(@order.customer_id)
  @products = Product.find(:all, :include=>[:items],:order=>["products.description"])
  @partners = Partner.find(:all, :order=>"company_name")
end

def get_reps
  @salesreps = Salesrep.find(:all,:order=>"fullname")
  @commission = Commission.new
  render :partial=>'commission'
end

在我的“订单”模型中,我有了这个:

 def commission_attributes=(commission_attributes)
  commission_attributes.each do |attributes|
    if attributes[:id].blank?
      commissions.build(attributes)
    else
      commission = commissions.detect{|t| t.id == attributes[:id].to_i}
      commission.attributes = attributes
    end
   end
 end

这适用于rails 2,但是在rails 3中我收到以下错误:

@order[commission_attributes]' is not allowed as an instance variable name</code></pre>

我似乎无法弄清问题是什么,或者如何解决这个问题..非常感谢任何帮助。

安德鲁

2 个答案:

答案 0 :(得分:2)

fields_for方法只接受对象或符号。如果没有更多的代码,很难给出具体的解决方案,但这样的事情可能有用:

<%= form_for @order do |form| %>
  ...
  <%= fields_for @order.commission do |commission_form| %>

在此处阅读:http://apidock.com/rails/v3.0.0/ActionView/Helpers/FormHelper/fields_for

答案 1 :(得分:1)

另一种选择是

<%= f.fields_for :commission, commission do |commission_form| %>

这应该导致提交触发commission_attributes=而不是直接搞乱另一个模型,并通过提供对象,您可以用所述对象填充表单。

但这只是另一种值得一提的方法。这是文档fields_for#Nested Attributes