我正在尝试通过 Categorizations 模型在 Products Controller 中建立与 ClothingSize 模型的关系。我收到“未经许可的参数:clothing_size”错误,因此从未建立关系。我认为 View 中的嵌套表单有问题,因为除非下面显示的符号是单数,否则我无法显示“大小”字段。我认为这可能指向另一个问题。
<%= form_for(@product) do |f| %>
<%= f.fields_for :clothing_size do |cs| %>
楷模
产品
class Product < ActiveRecord::Base
has_many :categorizations
has_many :clothing_sizes, through: :categorizations
accepts_nested_attributes_for :categorizations
end
分类
class Categorization < ActiveRecord::Base
belongs_to :product
belongs_to :clothing_size
accepts_nested_attributes_for :clothing_size
end
服装尺码
class ClothingSize < ActiveRecord::Base
has_many :categorizations
has_many :products, through: :categorizations
accepts_nested_attributes_for :categorizations
end
产品 Controller
def new
@product = Product.new
test = @product.categorizations.build
def product_params
params.require(:product).permit(:title, :description, :image_url, :image_url2, :price, :quantity, :color, :clothing_sizes => [:sizes, :clothing_size_id])
end
end
看法
<%= form_for(@product) do |f| %>
<%= f.fields_for :clothing_size do |cs| %>
<div class="field">
<%= cs.label :sizes, "Sizes" %><br>
<%= cs.text_field :sizes %>
</div>
<% end %>
<% end %>
最佳答案
在您看来,您有 :clothing_size
(单数)但在您的 product_params
你有的方法:clothing_sizes
(复数)。因为您的Product
型号has_many :clothing_sizes
,您希望它在您看来是复数形式。
<%= form_for(@product) do |f| %>
<%= f.fields_for :clothing_sizes do |cs| %>
此外,您需要构建一个
clothing_size
为您的product
在您的 Controller 中,并允许 :clothing_sizes_attributes
而不是 clothing
您的 product_params
中的尺寸方法。 (我会将您的 new
和 product_params
方法分开,将 product_params
设为私有(private),但这只是我。)def new
@product = Product.new
@clothing_size = @product.clothing_sizes.build
end
private
def product_params
params.require(:product).permit(:title, :description, :image_url, :image_url2, :price, :quantity, :color, :clothing_sizes_attributes => [:sizes, :clothing_size_id])
end
关于ruby-on-rails - Rails 4中与嵌套表单的多对多关系-未经允许的参数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24213858/