简体   繁体   中英

Rails - relation between activeadmin model and custom model

First I would like to know if there is any possibilities to associate one of my model with the ActiveAdmin::Comment and the AdminUser models

this is my model

class AdminAction < ActiveRecord::Base
  has_one :comment, :class_name => "ActiveAdmin::Comment", :foreign_key => "admin_action_id"
  belongs_to :admin_user
end

thoses associations don't raise any errors, just returning `nil``

I have added a field in thoses two models :

add_column :admin_users, :admin_action_id, :integer
add_column :active_admin_comments, :admin_action_id, :integer

The goal here is to fetch the AdminUser and the Comment associate to my new model AdminAction and when I do

a = AdminAction
a.admin_user 
# and 
a.comment

it works

any ideas ?

You need to have a admin_user_id in the admin_actions table to make this belongs_to association work.

class AdminAction < ActiveRecord::Base
  belongs_to :admin_user
end

Also, the foreign_key param is unneeded because it will be inferred from the AdminAction class name.

class AdminAction < ActiveRecord::Base
  has_one :comment, :class_name => "ActiveAdmin::Comment", :foreign_key => "admin_action_id"
end

Other than that, what you have should work as expected. If it is not, please provide more detail as to what you are seeing, or not seeing as the case may be.

I have this working, albiet with a User model rather than AdminUser . Here is my code:

Migrations

class CreateAdminAction < ActiveRecord::Migration
  def change
      create_table :admin_actions do |t|
      t.references :user, index: true
      t.timestamps
    end
  end
end

class AddFieldsForAdminAction < ActiveRecord::Migration
  def change
    add_column :active_admin_comments, :admin_action_id, :integer
  end
end

AdminAction class

class AdminAction < ActiveRecord::Base
  has_one :comment, class_name: 'ActiveAdmin::Comment'
  belongs_to :user
end

Another thought: if you are looking to get the ActiveAdmin::Comment records for a single AdminUser , I think you can fetch them directly like this:

admin_comments = ActiveAdmin::Comment.find_for_resource_in_namespace(AdminUser.find(some_id), :admin)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM