Configure Hirb to show relations?

103 Views Asked by At

I have two models:

class EventType < ActiveRecord::Base
  belongs_to :event_class
end

class EventClass < ActiveRecord::Base
  has_many :event_types
end

The schemas look like this:

  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

In the console I can inspect the first event_type easily enough:

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

But Hirb doesn't seem willing to follow this (excerpt from hirb.yml):

Try #1:

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

(Yeah, I know - I wasn't really expecting Hirb to devine that I was looking for a specific, but unnamed, field within the EventClass. I'm listing the try here for completeness)

Result #1:

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

Try #2:

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

Result #2:

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

Try #3:

Add a method on the EventType class:

  def event_class_description
     event_class.description
  end

Change the hirb.yml configuration to show this new method in place of the DB field:

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

Result #3:

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

But having to add methods for every relationship seems like I'm missing something.

0

There are 0 best solutions below