ActiveAdmin has_many通过关系不更新param Rails

时间:2015-04-22 22:40:37

标签: ruby-on-rails-4 activeadmin has-many-through formtastic

我正在努力在主动管理中创建一个has_many:through关系。以下是他们的模型:

 class Category < ActiveRecord::Base
   has_many :subcategories
 end

 class Subcategory < ActiveRecord::Base
   has_many :product_in_subcategories
   has_many :products, through: :product_in_subcategories
   accepts_nested_attributes_for :product_in_subcategories, :allow_destroy => true

   belongs_to :category
 end

 class Product < ActiveRecord::Base
   has_many :product_in_subcategories
   has_many :subcategories, through: :product_in_subcategories
   accepts_nested_attributes_for :product_in_subcategories, :allow_destroy => true
 end

 class ProductInSubcategory < ActiveRecord::Base
   belongs_to :product
   belongs_to :subcategory
 end

在ActiveAdmin中,我有permit_params,形式如下:

 ActiveAdmin.register Product do
   # note some params that are product only have been removed for simplicity
   permit_params :name, subcategory_id:[:id], product_in_subcategories_attributes: [:id, :subcategory_id, :product_id, :_create, :_update]

     form do |f|
       f.inputs

      f.has_many :product_in_subcategories do |s|
          s.input :subcategory_id, :as => :check_boxes, :collection => Subcategory.all
      end

      f.actions
    end
end

表单按原样填充,并保存除subcategory_id之外的所有内容。如果我在数据库中输入一个正确的子类别_id,则该框将显示在编辑时选中。

保存时的消息:

 Unpermitted parameters: subcategory_id

但是,它似乎正在尝试使用该产品提交此内容,而该产品没有子类别_id。关于我在做什么的任何想法都不正确吗?这让我疯狂,我已经阅读了我能找到的一切。我真的很想知道我做错了什么。感谢。

1 个答案:

答案 0 :(得分:2)

花了很多时间在这个上面,我找不到合适的解决方案,除了这个,这实际上是非常好的。事实上,它与我设想的解决方案没什么不同:

以上代码的唯一更改是在ActiveAdmin中进行的:

 ActiveAdmin.register Product do
    # note some params that are product only have been removed for simplicity
    permit_params :name, product_in_subcategories_attributes: [:id, :subcategory_id, :product_id, :_create, :_update]

      form do |f|
        f.inputs

        f.has_many :product_in_subcategories do |s|
           s.input :subcategory_id, :as => :select, :collection => Subcategory.all
        end

        f.actions
      end
 end

很奇怪这如何允许选择框没有问题,但它会在复选框上翻转。尽管如此,我对解决方案感到满意。