ruby-on-rails - Rails 4中与嵌套表单的多对多关系-未经允许的参数错误

标签 ruby-on-rails

我正在尝试通过 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 中的尺寸方法。 (我会将您的 newproduct_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/

相关文章:

ruby-on-rails - 启动 Ruby 应用程序

ruby-on-rails - PostgreSQL:按多个列权重排序

ruby-on-rails - 如何测试 Rails 应用程序在生产环境中是否正常工作

javascript - Twitter Typeahead 与预取 JSON

ruby-on-rails - 从头开始编写用户身份验证或使用 Gem - Rails?

ruby-on-rails - RoR 4 中带验证的正则表达式

ruby-on-rails - 跨同一用户的请求存储状态

ruby-on-rails - 带有 12 小时制的引导日期时间选择器未在 Rails 中显示子午线(上午或下午)?

ruby-on-rails - 如果其中一个数据库更新失败,rails db 事务不会回滚

javascript - Google Map API Marker 在 Ruby On Rails 中添加动态标签