【问题标题】:Rails Administrate - Customize has_manyRails Administrate - 自定义 has_many
【发布时间】:2020-03-22 09:21:23
【问题描述】:

我正在使用administrate gem。我有一组用户,并在该用户仪表板中显示has_many 关系。

现在,我的 user_dashboard 看起来像

class UserDashboard < Administrate::BaseDashboard
  # ATTRIBUTE_TYPES
  # a hash that describes the type of each of the model's fields.
  #
  # Each different type represents an Administrate::Field object,
  # which determines how the attribute is displayed
  # on pages throughout the dashboard.
  ATTRIBUTE_TYPES = {
    ...
    sub_items: Field::HasMany.with_options(limit: 10)
  }

现在,这在默认情况下有效,但问题是它为用户显示 all sub_items,这通常没问题,但我试图只 显示has_many 关系,如果它具有某种类型。例如,默认情况下我想要显示所有user.sub_items,我只想显示user.sub_items.where(category: [arr_of_options], sub_category: [arr_of_options])

我已经试过了

  • 传递此处显示的选项https://github.com/thoughtbot/administrate/blob/master/docs/customizing_dashboards.md,但Field::HasMany 没有集合/条件选项
  • 仅在视图中显示某个 has_many 集合,在本例中为admin/users/show.html.erb。这可能是可能的,但在这里这样做似乎真的很麻烦
  • 尝试在 admin/users_controller 中进行过滤,但我相信控制器只给了我 requested_resource 而不是该资源上的子对象

有人知道我如何只能在管理仪表板中显示某些 has_many 对象吗?

【问题讨论】:

    标签: ruby-on-rails administrate


    【解决方案1】:

    要仅显示 has_many 关系的特定范围,请执行以下操作。

    首先,在模型类上,创建一个新的 has_many 关系,与原始关系平行,但名称不同,具有所需的范围。例如,在与 Administrate 源代码捆绑在一起的示例应用程序中,我向 Customer 模型添加了 new_england_orders 关联:

     class Customer < ApplicationRecord
       has_many :orders, dependent: :destroy
    +  has_many :new_england_orders, ->{ where(address_state: %w{VT NH MA CT ME RI}) }, class_name: "Order"
       belongs_to :country, foreign_key: :country_code, primary_key: :code
       has_many :log_entries, as: :logeable
    

    其次,将此关系添加到您的仪表板(可能替换原来的),并确保添加class_name 选项,以便管理员知道要使用哪个仪表板:

         lifetime_value: Field::Number.with_options(prefix: "$", decimals: 2),
         name: Field::String,
         orders: Field::HasMany.with_options(limit: 2, sort_by: :id),
    +    new_england_orders: Field::HasMany.with_options(limit: 2, sort_by: :id, class_name: 'Order'),
         log_entries: Field::HasManyVariant.with_options(limit: 2, sort_by: :id),
         updated_at: Field::DateTime,
         kind: Field::Select.with_options(collection: Customer::KINDS),
    

    您的新范围关联现在应该出现在您的仪表板上。

    【讨论】:

    • 就是这样,我忘记了我之前尝试过的class_name 属性。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2022-09-23
    • 2011-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    相关资源
    最近更新 更多