Search code examples
ruby-on-railsruby-on-rails-5activeadminpolymorphic-associations

Rails ActiveAdmin - pass polymorphic association parameters in link_to new


I'm new to ActiveAdmin and I have this problem:

I have two models: Picture and Content. Picture has many contents through polymorphic association.

I succeeded to make the button "Create content" from Picture show page pass contentable_type and picture id as contentable in the new_admin_content request as parameters using the following in app/admin/picture.rb :

action_item :new, only: :show do
  link_to "Add content", new_admin_content_path(contentable_type: "Picture", contentable: picture)
end

and to receive the parameters I wrote the following in app/admin/content.rb :

permit_params :list, :of, :attributes, :on, :model, :contentable, :contentable_type

form do |f|
  f.object.contentable_type = params[:contentable_type]
  f.object.contentable = params[:contentabl]
  puts f.object.contentable_type
  puts f.object.contentable
  f.inputs "Details" do
    .
    .
    .
  end
  actions
end

But in this case, I get this error:

NoMethodError in Admin::Contents#new

undefined method `primary_key' for String:Class

The error is triggered by line f.object.contentable = params[:contentable]

When I pass only contentable_type to f.object whithout passing contentable, f.object saves contentable_type in its field, but submitting the form doesn't create a new record.

How can I save contentable as in its form field and succeed to make a create action on form submit?


Solution

  • The problem was solved by changing f.object.contentable = params[:contentabl] to f.object.contentable_id = params[:contentabl] (like the column name in the database) and adding all form parameters to permitted params