【问题标题】:How to set permit_params for another model如何为另一个模型设置 permit_params
【发布时间】:2016-08-04 10:01:50
【问题描述】:

这些是我的模型:

Product.rb

class Product < ApplicationRecord
  belongs_to :position
  has_many :products_sizes
  has_many :sizes, through: :products_sizes
  has_many :reviews, dependent: :destroy
  accepts_nested_attributes_for :products_sizes
end

Products_size.rb

class ProductsSize < ApplicationRecord
  belongs_to :product
  belongs_to :size
  has_many :prices
  accepts_nested_attributes_for :prices
end

大小.rb

class Size < ApplicationRecord
  has_many :products_sizes
  has_many :products, through: :products_sizes
end

Price.rb

class Price < ApplicationRecord
  belongs_to :products_size
end

在 ActiveAdmin 中,我需要为产品制作一个表单,因为当我更新产品时,我可以创建一个价格,所以表单的一部分如下所示:

... #here is the begining of the form
f.inputs 'Sizes' do
          f.semantic_fields_for ProductsSize.where(product_id: params[:id], size_id: Product.find(params[:id]).products_sizes.size.to_i).first.prices.new do |ps|
            ps.input :products_size_id, label: 'Size', as: :select, collection: Product.find(params[:id]).sizes.map { |s| ["#{s.title}", s.id] }
            ps.input :quantity
            ps.input :amount
            li do
              link_to 'Add size', '#'
            end
          end
        end

这一切似乎都很好,除了单击提交按钮时,没有创建价格。我认为,那是因为permit_params 没有为price 指定。我该如何指定它们?谢谢。

【问题讨论】:

    标签: ruby-on-rails associations activeadmin


    【解决方案1】:
     ActiveAdmin.register Post do
       permit_params :title,
                     comments_attributes: [:name, :hidden]
     end
    

    Post 是一种穆德尔,而 cmets 是另一种。您可以使用 cmets_attributes 中的参数,如果您的模型名称是价格,您可以使用 price_attributes: [...params...]。

    【讨论】:

      【解决方案2】:

      这是您在active admin 中允许参数的方式

      ActiveAdmin.register Post do
      permit_params :title, :content, :author
      end
      

      这只是一个例子,使用你自己的参数

      【讨论】:

      • 是的,但我需要设置permit_params 不是为我的Product 模型,而是为Price,它具有belongs_to :products_size 关系。我通过ProductsSize 模型到达Price
      • 您是否允许控制器中的参数?
      猜你喜欢
      • 2010-10-18
      • 1970-01-01
      • 1970-01-01
      • 2021-07-06
      • 2014-04-09
      • 2016-02-04
      • 1970-01-01
      • 1970-01-01
      • 2011-10-09
      相关资源
      最近更新 更多