简体   繁体   English

rails_admin 通过嵌套的belongs_to 关联搜索

[英]rails_admin search through nested belongs_to association

I have a model:我有一个模型:

class TenantReference < ActiveRecord::Base
  include TenantReferenceAdmin
  belongs_to :tenant, inverse_of: :reference
  default_scope { eager_load(:tenant) }
end

and a Tenant model:和租户模型:

class Tenant < ActiveRecord::Base
  default_scope { eager_load(:user) }
  belongs_to :user
end

and a User model:和用户模型:

class User < ActiveRecord::Base
  has_many :tenants, :foreign_key => :user_id, class_name: 'Tenant'
end

and finally a TenantReferenceAdmin rails admin file:最后是一个 TenantReferenceAdmin rails 管理文件:

module TenantReferenceAdmin
  extend ActiveSupport::Concern

  included do
    rails_admin do
      list do
        field :tenant do
          filterable true
          queryable true
          searchable [ :first_name, :last_name]
        end
    ...

what I'm trying to achieve is that in the tenantreference admin page the user can search TenantReference objects by the first_name or last_name of the user through their Tenant reference.我想要实现的是,在tenantreference 管理页面中,用户可以通过其租户引用按用户的 first_name 或 last_name 搜索 TenantReference 对象。

This configuration is producing a postgresql query like:此配置正在生成一个 postgresql 查询,如:

SELECT  "tenant_references"."id" AS t0_r0, .... "tenants"."id" AS t1_r0, ......
FROM "tenant_references" LEFT OUTER JOIN "tenants" ON "tenants"."id" = "tenant_references"."tenant_id" 
WHERE ((tenants.first_name ILIKE '%query%') 
  OR (tenants.last_name ILIKE '%query%') 
ORDER BY tenant_references.id desc LIMIT 20 OFFSET 0)

which doesn't work, because first/last_name are actually fields of user, not of tenant.这不起作用,因为 first/last_name 实际上是用户的字段,而不是租户的字段。

how could I fix this?我怎么能解决这个问题?

Thanks,谢谢,

The problem seems to be that rails admin only adds JOIN to the query if the current model has a direct link ( has_many , has_one ...) to the other model to search in. and it joins it if the corresponding field is marked as queryable true .问题似乎是,如果当前模型具有到另一个模型的直接链接( has_manyhas_one ...),则 rails admin 仅将JOIN添加到查询中以进行搜索。如果相应的字段被标记为queryable true ,则它会加入它queryable true

so I changed adding to the references model this line:所以我改变了添加到参考模型这一行:

has_one :user, through: :tenant

I then created an invisible list field:然后我创建了一个不可见的列表字段:

    field :user do
      visible false
      queryable true
      searchable [{User => :first_name}, {User => :last_name}]
    end

that can be searched upon, but it's not shown in the list.可以搜索,但未显示在列表中。

this has solved the issue, I don't consider this ideal as I had to modify my model in order to be able to perform rails_admin search, when rails_admin could have handled this situation without changing the code.这已经解决了这个问题,我不认为这是理想的,因为我必须修改我的模型才能执行 rails_admin 搜索,而 rails_admin 可以在不更改代码的情况下处理这种情况。 But for now I can live with this但现在我可以忍受这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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