ActiveAdmin不会保存有很多,属于很多字段



我有两个模型。类别和职位。它们使用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)

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

最好的祝愿,马特

在AA中试试:

    controller do
      def permitted_params
        params.permit post: [:title, :body, :meta_keywords, :meta_description, :excerpt, :image, category_ids: []]
      end
    end

在/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

我已经测试过了,这可能适用于您和其他人

# 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

记住,如果你使用强参数,也要允许使用属性(参见上面的zarazan答案:D)

引用自http://rails.hasbrains.org/questions/369

最新更新