0

我已经更新了这个问题,以反映那些提出建议的人的意见。

在具有引导程序和简单表单的 Rails 3.2 应用程序中,发票模型中有以下内容:

has_many :line_items
accepts_nested_attributes_for :line_items
attr_accessible :user_id, :project_name, :date1, :date2, :date3, :paid, :memo, :line_items_attributes

在 line_item 模型中:

belongs_to :invoice
# validates_presence_of :invoice_id (COMMENTED THESE OUT to generate a clearer error)
# validates_uniqueness_of :invoice_id

在我的发票控制器中,我有:

  def new
     @users = User.find(:all, :order => "username asc")

     @line_items = [] # got "undefined method `<<' for nil:NilClass" until defined as array
     Product.find(:all, :order => "position asc").each do |p|
        @line_items << LineItem.new(:product_id => p.id, :cost => p.unit_cost, :name => p.name, :description => p.description, :position => p.position, :quantity => 0)
     end

     @invoice = Invoice.new(:line_items_attributes => @line_items) # PRODUCING ERROR
  end

在我的表格中,我有以下内容:

<%= simple_form_for @invoice do |f| %>
    <%= f.input :user_id, :collection => @users.map(&:username) %>
    <%= f.input :project_name %>
    <%= f.input :date1, :as => :date, :order => [:month, :day, :year], :label => "3rd Invoice" %>

    <%= f.simple_fields_for :line_items do |li_fields| %>
        <%= li_fields.input :name %>
        <%= li_fields.input :quantity %>
        <%= li_fields.input :unit_cost %>
    <% end %>

    <%= f.button :submit, "Save", :class => "btn btn-primary" %>
<% end %>

再次在我的控制器中:

  def create
    @invoice = Invoice.new(params[:invoice])

    respond_to do |format|
      if @invoice.save
         ...
      else
         ...
      end
    end
  end

错误信息:

undefined method `with_indifferent_access' for #<LineItem:0x007ffc9ebc0730>

p @line_items 产生:

[#<LineItem id: nil, invoice_id: nil, product_id: 5, cost: #<BigDecimal:7ffc9e45d330,'0.69E2',9(18)>, name: "Account", description: "Account", quantity: 0, position: 2, created_at: nil, updated_at: nil>, 
 #<LineItem id: nil, invoice_id: nil, product_id: 12, cost: #<BigDecimal:7ffc9e45c9f8,'0.3E3',9(18)>, name: "Consultant Training", description: "Consultant Training", quantity: 0, position: 12, created_at: nil, updated_at: nil>]

谢谢你的帮助。

4

1 回答 1

1

您的问题出在您的表单设置中。你@invoice.line_items.each_with_index do |line_item, index|在你的 f.simple_fields_for 之前有,你不需要它。相反,您应该...

<%= simple_form_for(@invoice) do |f| %>
    ...some inputs    
    <%= f.simple_fields_for :line_items do |li_fields| %>
        ...more inputs
    <% end %>
<% end %>

然后,在您的发票模型中,您要确保使line_items_attributesattr_accessible。

于 2013-02-28T02:04:49.363 回答