1

我有两个模型:

class EventType < ActiveRecord::Base
  belongs_to :event_class
end

class EventClass < ActiveRecord::Base
  has_many :event_types
end

架构如下所示:

  create_table "event_classes", force: true do |t|
    t.string   "domain"
    t.string   "description"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "event_types", force: true do |t|
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "known_as"
    t.text     "code"
    t.integer  "event_class_id"
  end

在控制台中,我可以很容易地检查第一个 event_type:

et1 = EventType.first
et1.event_class.description
=> "Standard Events for Foos in Bars"

但 Hirb 似乎不愿意遵循这一点(摘自 hirb.yml):

尝试#1:

EventType:
    :options:
        :fields:
            - id
            - code
            - known_as
            - event_class

(是的,我知道 - 我真的不希望 Hirb 认为我在 EventClass 中寻找一个特定但未命名的字段。为了完整性,我在这里列出了尝试)

结果#1:

+----+------+--------------------------------+--------------------------------+
| id | code | known_as                       | event_class                    |
+----+------+--------------------------------+--------------------------------+
| 1  | foo  | Standard Foo from Bar example  | #<EventClass:0x007ff0b5d458c0> |
+----+------+--------------------------------+--------------------------------+

尝试#2:

EventType:
    :options:
        :fields:
            - id
            - code
            - known_as
            - event_class.description

结果#2:

Hirb Error: undefined method `event_class.description' for #<EventType:0x007f82748d10f0>

尝试#3:

在 EventType 类上添加一个方法:

  def event_class_description
     event_class.description
  end

更改 hirb.yml 配置以显示此新方法来代替 DB 字段:

    EventType:
    :options:
        :fields:
            - id
            - code
            - known_as
            - event_class_description

结果#3:

+----+------+--------------------------------+----------------------------------+
| id | code | known_as                       | event_class_description          |
+----+------+--------------------------------+----------------------------------+
| 1  | foo  | Standard Foo from Bar example  | Standard Events for Foos in Bars |
+----+------+--------------------------------+----------------------------------+

但是必须为每个关系添加方法似乎我错过了一些东西。

4

0 回答 0