【问题标题】:ActiveRecord::AssociationTypeMismatch in Controller#create控制器中的 ActiveRecord::AssociationTypeMismatch#create
【发布时间】:2015-03-23 05:35:57
【问题描述】:

我正在编写一个 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 中的 create 方法:

  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

【问题讨论】:

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


    【解决方案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)
    

    【讨论】:

    • 感谢您的详细回复。但是,当我进行您建议的更改时,我得到: ActionView::Template::Error: undefined method `restaurant_id' for #<0x007fbd608e8990>
    【解决方案2】:

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

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

    【讨论】:

    • 我没有从中得到错误,但表单下拉列表中的值只是 ID。我将您的建议重新排序为 (:name, :id),因此下拉菜单显示了正确的值,但我仍然收到 AssociationTypeMismatch: 错误。还有什么我应该看的吗?
    • 当我尝试得到:#<0x007fbd5d587ee8>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 2016-06-11
    • 2015-10-04
    • 2017-07-08
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    相关资源
    最近更新 更多