1

我在表单中使用collection_select,并且在预期对象但收到字符串的地方不断收到错误消息。我该如何解决这个问题?我的 collection_select 语法有什么问题吗?我希望将一个新的 LineItems 对象与产品可用的 Color 对象传递给这个新对象。以下是我的代码和错误:

产品/show.html.erb

<%= form_for LineItem.new do |f| %>
        <%= f.collection_select :color_id, @product.colors.all, :id, :name, { prompt: 'Select a Color' } %>
        <%= f.text_field :quantity %>
        <%= f.hidden_field :product, :value => @product %>
        <%= f.submit %>
<% end %>

控制器/line_items_controller.rb

class LineItemsController < ApplicationController
  def new
    @line_item = LineItem.new
  end
  def create
    @line_item = LineItem.create!(params[:line_item].merge(:cart => current_cart))
    flash[:notice] = "Added #{@product.name} to cart."
    redirect_to current_cart_url
  end
end

模型/line_item.rb

class LineItem < ActiveRecord::Base
  attr_accessible :cart_id, :product_id, :quantity, :unit_price, :product, :cart, :color_id, :color
  belongs_to :cart
  belongs_to :product
  has_one :color
end

移民

class CreateLineItems < ActiveRecord::Migration
  def change
    create_table :line_items do |t|
      t.decimal :unit_price
      t.integer :product_id
      t.integer :cart_id
      t.integer :color_id
      t.integer :size_id
      t.integer :extra_id
      t.integer :quantity

      t.timestamps
    end
  end
end

错误

ActiveRecord::AssociationTypeMismatch at /line_items
Product(#40266200) expected, got String(#18896220)

ActiveRecord::Associations::BelongsToAssociation#raise_on_type_mismatch
activerecord (3.2.13) lib/active_record/associations/association.rb, line 204
ActiveRecord::Associations::BelongsToAssociation#replace
activerecord (3.2.13) lib/active_record/associations/belongs_to_association.rb, line 6
ActiveRecord::Associations::BelongsToAssociation#writer
activerecord (3.2.13) lib/active_record/associations/singular_association.rb, line 17
block in LineItem#order=
activerecord (3.2.13) lib/active_record/associations/builder/association.rb, line 51
block in LineItem#assign_attributes
activerecord (3.2.13) lib/active_record/attribute_assignment.rb, line 85
LineItem#assign_attributes
activerecord (3.2.13) lib/active_record/attribute_assignment.rb, line 78
LineItem#initialize
activerecord (3.2.13) lib/active_record/base.rb, line 498
LineItem.create!
activerecord (3.2.13) lib/active_record/validations.rb, line 39
LineItemsController#create
app/controllers/line_items_controller.rb, line 6

任何帮助都将不胜感激。

4

1 回答 1

3

问题似乎在于您尝试创建新订单项的方式。您正在通过product视图中的隐藏字段传递对象,该字段最终将转换为类似于#<Product:0xc412bdc>呈现 html 时的字符串,因此在提交表单时它将作为字符串传递。

因此,您可能需要通过以下形式传递product_id而不是:product

<%= f.hidden_field :product_id, :value => @product.id %>

现在这应该可以了。

于 2013-06-24T17:51:31.207 回答