活跃的管理员和 has_one

Active Admin and has_one

我试图让我的用户模型在 ActiveAdmin 中工作,但它似乎只在我将模型引用回用户模型本身时才有效,这会破坏我在应用程序中的表单。

这种方式破坏了我的 ActiveAdmin 用户视图,但通过表单在我的应用程序中工作。

user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :vehicle
  has_one :permit
  has_one :faculty
  has_one :emergency_contact
  has_one :student

  def admin?
    roles == "admin"
  end

  def editor?
    roles == "editor"
  end

  def standard?
    roles == "standard"
  end

end

user.rb

has_many :vehicle, class_name: 'User'
has_one :permit, class_name: 'User'
has_one :faculty, class_name: 'User'
has_one :emergency_contact, class_name: 'User'
has_one :student, class_name: 'User'

第二种方法是让我的 ActiveAdmin 用户视图起作用(我知道这是错误的,只是不知道如何修复它)但是它破坏了我应用程序中的表单。当 ActiveAdmin 损坏时,我收到错误消息: undefined method 'vehicle_id_eq' for Ransack::Search<class: User 当我在 ActiveAdmin 中单击用户视图时。

有人知道我可以做些什么来修复我的模型以使 ActiveAdmin 正常工作吗?

编辑**

admin/user.rb

ActiveAdmin.register User do
    permit_params :roles
end

models/vehicle.rb

class Vehicle < ApplicationRecord
    belongs_to  :user
end

ActiveAdmin 正在尝试为用户模型上的所有关联创建过滤器。这似乎包括您的 has_many 关联(我猜也包括 has_one)。这是一个如此简单的案例,AA 试图默认为 has_onehas_many 关联创建过滤器似乎有问题。可能值reporting on Github。同时,有几种方法可以解决这个问题。

  1. 指定您自己的过滤器

admin/user.rb

ActiveAdmin.register User do
    permit_params :roles

    filter :name
    filter :email
    # or you can remove filters with => remove_filter :vehicles
    #... add more filters that as you need.
end

这样您就拥有了实际用于查找单个或一组用户的过滤器。

  1. 您可以joininclude正在引用的模型。如果您确实计划按任何这些关联 过滤用户,我只推荐这个 。如果没有,请使用上面提到的第一种方法。

admin/user.rb

ActiveAdmin.register User do
    permit_params :roles

    controller do
      active_admin_config.includes.push :vehicles, :permit #,... etc.

      # IF YOU INCLUDE A `has_many`, you need to ensure you are not 
      # returning duplicate resources. So you need to overwrite
      # the apply_filtering method
      def apply_filtering(collection)
        super.where(User.primary_key => collection)
      end
    end
end