RoastsController #create中的ActiveRecord :: AssociationTypeMismatch

时间:2018-02-08 11:48:57

标签: ruby-on-rails activerecord

这对我来说是一个新错误,并且正在努力解决它。它还指出:name Hayden Rock Gates Vishal Cameroon Micky Michael Tony Waugh Tom Tommy Avinash Shreyas Ramesh Adam

它在我的烘焙控制器中突出显示我的创建方法:

Roaster(#70130698993440) expected, got "1" which is an instance of String(#70130675908140)

场景是我尝试创建三重嵌套表单。对于三个模型 def create @roast = Roast.new(roast_params) RoastsCountries,其中烤肉有很多国家和地区有很多地区。

我假设烤火山有问题,但我能看出它是什么。我在那里添加了嵌套模型的关联

Regions

我的表单

def roast_params
  params.require(:roast).permit(:roaster, :name, :bestfor, :beans, :roast, :tastingnotes, :notes, :slug, :avatar, :countries_attributes => [:country_name, :regions_attributes => [:region_name]])
end

烤肉控制器

  <div class="form-group">
    <%= form.fields_for :countries do |countries_form| %>
      <%= countries_form.label :country %>
      <%= countries_form.text_field :name, class: "form-control" %>

  </div>
    <div class="form-group">
      <%= form.fields_for :regions do |regions_form| %>
        <%= regions_form.label :region %>
        <%= regions_form.text_field :region_name, class: "form-control" %>
      <% end %>
    <% end %>
  </div>

烤模型

...
  def new
    @roast = Roast.new
    @roast.countries.build.regions.build
  end
...

国家/地区模型

class Roast < ApplicationRecord
  has_many :tastings
  has_many :countries
  has_many :notes, through: :tastings
  has_many :comments, as: :commentable
  belongs_to :roaster
  accepts_nested_attributes_for :countries

区域模型

class Country < ApplicationRecord
  has_many :regions, inverse_of: :country
  accepts_nested_attributes_for :regions
  belongs_to :roasts

我在国家参数中嵌套了区域参数,这是正确的吗?我还在其他问题上看到了在class Region < ApplicationRecord belongs_to :country 中将config.cache_classes设置为true的建议,但这对此没有帮助。

更新 因此,我认为它与嵌套表单无关,而是与我使用的collection_select无关。

development.rb

因此,此选择会从名为<%= form.label :roaster, class: 'control-label' %> <%= form.collection_select(:roaster, Roaster.order(:roaster_name).all, :id, :roaster_name, prompt: true, class: "form-control") %> 的模型中提取roaster_name

我的参数现在如下所示:

Roaster

在提交表单时查看控制台,似乎只是:Roaster的id被传递,而不是值:roaster_name。

  params.require(:roast).permit(:roaster_name, :roaster, :name, :bestfor, :beans, :roast, :tastingnotes, :notes, :slug, :avatar, :countries_attributes => [:country_id, :country_name, :regions_attributes => [:region_id, :region_name]])

无法解决这个问题

1 个答案:

答案 0 :(得分:0)

当使用不是预期类的实例的值调用关联设置器(在这种情况下为Roast#roaster=)时,会引发

ActiveRecord::AssociationTypeMismatch。预计会Roaster,得到String

问题似乎在于将roaster作为一个参数传递,这是&#34; 1&#34;您的示例中的(字符串)。我猜这实际上是一个Roaster的ID,问题中的表单代码没有显示出来。

也许您打算允许并传递roaster_id param?

def roast_params
  params.require(:roast).permit(:roaster_id, # ... 
end
相关问题