Controller#create中的ActiveRecord :: AssociationTypeMismatch

时间:2015-03-23 05:35:57

标签: ruby-on-rails ruby-on-rails-4 activerecord haml

我正在使用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'

我知道有很多类似的问题,我尝试了很多解决方案,但到目前为止还没有一个有效。这个错误表明什么是正确的解决方案?

以下是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

2 个答案:

答案 0 :(得分:1)

如果参数名称为restaurant,则Review.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)

答案 1 :(得分:1)

我假设你要做的是:

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