ActiveRecord::AssociationTypeMismatch 在 Controller#create 中

ActiveRecord::AssociationTypeMismatch in Controller#create

我正在 Rails 4.2 应用程序中处理一个基本表单,该应用程序提交一个餐厅评论表单。但是,当我的测试运行时出现以下错误:

 Failure/Error: click_button "Submit review"
 ActiveRecord::AssociationTypeMismatch:
   Restaurant(#70225646207060) expected, got String(#70225618208620)
 # ./app/controllers/reviews_controller.rb:12:in `create'

我知道有很多类似的问题,我已经尝试了很多解决方案,但到目前为止 none 已经奏效。此错误指示什么以及正确的解决方案是什么?

这是 reviews_controller.rb 的创建方法:

  def create
    Review.create!(params[:review].permit(:restaurant, :presentation, :service, :atmosphere, :comment))
    redirect_to root_path
  end

新的评论表单 (haml),我遗漏了其他文本输入字段:

  = form_for @review do |f|
    = f.label :restaurant  
    = f.collection_select(:restaurant, Restaurant.all, :id, :name)

    = f.submit "Submit review"

review.rb 型号:

class Review < ActiveRecord::Base
  belongs_to :restaurant
end

使用参数名称 restaurantReview.create! 将使用 Review 的 restaurant= 方法,该方法需要 Restaurant 对象。

如果您改用 restaurant_id 作为您的参数,它应该可以工作。

# controller
Review.create!(params[:review].permit(:restaurant_id, :presentation, :service, :atmosphere, :comment))

# form
= f.collection_select(:restaurant_id, Restaurant.all, :id, :name)

我假设您正在尝试执行以下操作:

= f.select :restaurant, Restaurant.pluck(:id, :name)