ActiveAdmin unpermitted param on有很多:通过关联

时间:2016-11-03 11:07:17

标签: ruby-on-rails activeadmin

我经历了大约12个与此类似的StackOverflow问题,但它们似乎都没有帮助我。

主动管理员: Article.rb

permit_params tag_ids: []
...
f.input :tag, as: :check_boxes, collection: Tag.all.map { |h|  [h.name, h.id] }

标签:

class Tag < ApplicationRecord
  has_many :taggings
  has_many :articles, through: :taggings

的Tagging:

class Tagging < ApplicationRecord
  belongs_to :article
  belongs_to :tag
end

文章:

class Article < ApplicationRecord
  belongs_to :category
  has_many :taggings
  has_many :tags, through: :taggings

我尝试允许以下内容:

  • tag_ids:[]
  • tag_ids:[:id]
  • tag_attributes:[:id]

获得:

found unpermitted parameter: hashtag

缺少一些东西!

UPD 1

这是我的日志:

[INFO ] === Processing by Admin::ArticlesController#update as HTML
[INFO ]   Parameters: {"utf8"=>"✓", "authenticity_token"=>"...", "article"=>{"tag"=>["", "1", "2"] ...}, "commit"=>"Update Article", "id"=>"1"}
[DEBUG]   AdminUser Load (2.1ms)  SELECT  "admin_users".* FROM "admin_users" WHERE "admin_users"."id" = $1 ORDER BY "admin_users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
[DEBUG]   Article Load (0.4ms)  SELECT  "articles".* FROM "articles" WHERE "articles"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
[DEBUG] Unpermitted parameter: tag

2 个答案:

答案 0 :(得分:1)

首先,accepts_nested_attributes_for通过添加此内容,"article"=>{"tag"=>["", "1", "2"] ...}将转换为"article"=>{"tags_attributes"=>["", "1", "2"] ...}

class Article < ApplicationRecord
   belongs_to :category
   has_many :taggings
   has_many :tags, through: :taggings

   accepts_nested_attributes_for :tags, :allow_destroy => true
end

在文章的控制器中,

在强参数列表中添加tags_attributes: [:id]。这将解决您的问题。

快乐编码。

答案 1 :(得分:1)

我设法解决了这个问题。有两种方法可以达到预期的效果。

动态添加/删除AA中的标签。

感谢来自@ user100693的提示,通过在我的文章模型中添加accepts_nested_attributes,我能够动态添加/删除所需的标签,但是我必须添加

accepts_nested_attributes_for :taggings, allow_destroy: true,不是:tags

允许的属性是:

taggings_attributes: [:id, :_destroy, :tag_id]

AA表格代码:

  f.has_many :taggings, allow_destroy: true, new_record: true do |h|
    h.input :tag
  end

多个选择复选框

这是我尝试实现的理想结果 - 通过复选框将文章分配给标签。原来,我需要对原始代码进行的唯一更改(请参阅问题)是:

有效管理员Article.rb

允许参数:tag_ids:[]

表格:f.input :tags, as: :check_boxes

而不是遍历Hash。那就是它。

相关问题