BreadnButter
BreadnButter

Reputation: 11

Rails 4 has many through with active admin

I am trying to set up a standard relationship as following:

class Category < ActiveRecord::Base
  has_many :post_categories
  has_many :posts, :through => :post_categories
  accepts_nested_attributes_for :post_categories
end

class Post < ActiveRecord::Base
  has_many :post_categories
  has_many :categories, :through => :post_categories
  accepts_nested_attributes_for :post_categories
  attr_accessor :category_ids
end

class PostCategory < ActiveRecord::Base
  belongs_to post
  belongs_to category
end

I am using ActiveAdmin and need to set up checkboxes to describe the relationship. I have tried many different ways to have the checkboxes save. Here is my admin post.rb file:

ActiveAdmin.register Post do

  permit_params :content, category_ids: []

  form do |f|
    f.inputs # Include the default inputs
    f.inputs "Categories" do
      f.input :categories, as: :check_boxes, collection: Category.all
    end
    f.actions # Include the default actions
  end
end

I have tried different permit params such as

permit_params :content, :categories
permit_params :content, post_categories_attributes: [:id, :post_id, :category_id]
permit_params :content, category_ids: [:id]

The database is set up as shown in the rails tutorial, and the relationship seems to work elsewhere except for being saved from activeadmin. I even tried to use param.permit! to permit all params, but still no luck.

I have found many posts of seemingly the same question, but many give different answers and nothing seems to work.

What is wrong?

Upvotes: 1

Views: 1530

Answers (1)

okliv
okliv

Reputation: 3959

Little late but this question is googled first for me, so I assume it can be helpful to other "googlers"

#models/post.rb

accepts_nested_attributes_for :categories#, allow_destroy: true

#AA Post conf file

permit_params :content, category_ids: []

Upvotes: 2

Related Questions