ActiveAdmin won't save has many and belongs to many field

浪尽此生 提交于 2019-12-22 04:37:13

问题


I have 2 models. Category and Post. They are connected using a has_many_and_belongs_to_many relationship. I checked in the rails console and the relationship works.

I created checkboxes in activeadmin to set the post categories using this form field:

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

The problem is when I try to save it because every other field data (title, body, meta infos etc.) is saved, but the category stays the same even if I unchecked it, or checked another too.

I am using strong parameters like this:

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

Please give me some suggestions to make active admin save the categories too!

Best Wishes, Matt


回答1:


Try this in AA:

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



回答2:


Put something like this in /app/admin/post.rb:

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

If you are using accepts_nested_attributes_for then it would look like this:

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



回答3:


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



来源:https://stackoverflow.com/questions/17200852/activeadmin-wont-save-has-many-and-belongs-to-many-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!