8

我有2个模型。类别和帖子。它们使用 has_many_and_belongs_to_many 关系连接。我检查了rails控制台并且关系有效。

我在 activeadmin 中创建了复选框以使用此表单字段设置帖子类别:

f.input :categories, as: :check_boxes, collection: Category.all

问题是当我尝试保存它时,因为所有其他字段数据(标题、正文、元信息等)都已保存,但即使我取消选中它或也检查了另一个,类别仍保持不变。

我正在使用这样的强参数:

post_params = params.require(:post).permit(:title,:body,:meta_keywords,:meta_description,:excerpt,:image,:categories)

请给我一些建议,让活跃的管理员也保存类别!

最好的祝愿,马特

4

3 回答 3

10

在 AA 中试试这个:

    controller do
      def permitted_params
        params.permit post: [:title, :body, :meta_keywords, :meta_description, :excerpt, :image, category_ids: []]
      end
    end
于 2013-07-11T10:18:39.987 回答
4

在 /app/admin/post.rb 中加入这样的内容:

ActiveAdmin.register Post do
  permit_params :title, :body, :meta_keywords, :meta_description, :excerpt, :image, category_ids: [:id]
end

如果您使用的是accepts_nested_attributes_for,那么它看起来像这样:

ActiveAdmin.register Post do
  permit_params :title, :body, :meta_keywords, :meta_description, :excerpt, :image, categories_attributes: [:id]
end
于 2013-12-08T02:32:40.433 回答
0

I've tested, this might works for you and others as well

# This is to show you the form field section
form do |f|
    f.inputs "Basic Information" do
        f.input :categories, :multiple => true, as: :check_boxes, :collection => Category.all
    end
    f.actions
end

# This is the place to write the controller and you don't need to add any path in routes.rb
controller do
    def update
        post = Post.find(params[:id])
        post.categories.delete_all
        categories = params[:post][:category_ids]
        categories.shift
        categories.each do |category_id|
            post.categories << Category.find(category_id.to_i)
        end
        redirect_to resource_path(post)
    end
end

Remember to permit the attributes if you're using strong parameters as well (see zarazan answer above :D)

References taken from http://rails.hasbrains.org/questions/369

于 2014-06-30T08:49:15.520 回答