我在表单中使用collection_select并且我一直收到一个错误,其中一个对象是预期的但是收到了一个String。我该如何解决这个问题?我的collection_select语法有什么问题吗?我想要一个新的LineItems对象,其中Color对象可用于传递给这个新对象。以下是我的代码和错误:
<%= 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 %>
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
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
完全赞赏任何帮助。
答案 0 :(得分:3)
问题似乎在于您尝试创建新订单项的方式。您正在将product
对象传递到视图中的隐藏字段,该字段最终会在呈现html时转换为类似#<Product:0xc412bdc>
的字符串,因此在提交表单时它将作为字符串传递
因此,您可能需要通过以下格式传递product_id
而不是product
:
<%= f.hidden_field :product_id, :value => @product.id %>
现在这应该有效。