ActiveAdmin won't save has many and belongs to many field
Asked Answered
B

3

8

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

Black answered 19/6, 2013 at 20:37 Comment(0)
G
10

Try this in AA:

    controller do
      def permitted_params
        params.permit post: [:title, :body, :meta_keywords, :meta_description, :excerpt, :image, category_ids: []]
      end
    end
Gurdwara answered 11/7, 2013 at 10:18 Comment(0)
P
4

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
Prurient answered 8/12, 2013 at 2:32 Comment(0)
J
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

Jacobs answered 30/6, 2014 at 8:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.