【发布时间】:2018-02-08 23:37:28
【问题描述】:
这对我来说是一个新错误,正在努力解决它。它还指出:Roaster(#70130698993440) expected, got "1" which is an instance of String(#70130675908140)
它突出显示了我在 Roasts 控制器中的创建方法:
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
我已经将区域参数嵌套在国家参数中,对吗?我还看到了关于在development.rb 中将config.cache_classes 设置为true 的建议的其他问题,但这在这里没有帮助。
更新 因此,进一步研究,我相信它与嵌套表单无关,而是我正在使用的 collection_select。
<%= form.label :roaster, class: 'control-label' %>
<%= form.collection_select(:roaster, Roaster.order(:roaster_name).all, :id, :roaster_name, prompt: true, class: "form-control") %>
所以这个选择是从一个名为Roaster的模型中提取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]])
在提交表单时查看控制台,似乎只有 Roaster 的 :id 被传递,而不是 :roaster_name 的值。
{"utf8"=>"✓",
"authenticity_token"=>"EG+zty85IiVsgipm1pjSAEZ7M66ELWefLq8Znux+cf89sSnVXxielRr1IaSS9+cJvdQD8g1D4+v2KqtKEwh6gw==",
"roast"=>{"roaster"=>"1", "name"=>"Espress", "countries_attributes"=>{"0"=>{"country_name"=>"UK"}}, "regions"=>{"region_name"=>"Highlands"}, "bestfor"=>"", "roast"=>"", "tastingnotes"=>""},
"commit"=>"Create Roast"}
无法解决
【问题讨论】:
-
为什么要使用roaster_name?假设您想将现有的 Roaster 分配给 Roast,您应该考虑将
roast_id从表单传递到 Roastcreate操作。 -
你必须在烤参数中发送
roaster_id -
你能粘贴你的
collection_select,你想给出错误吗? -
刚刚添加了收藏集。
标签: ruby-on-rails activerecord