在 Rails 4 中通过 Grape 实体呈现 `belongs_to` 关联

Presenting `belongs_to` association via Grape Entity in Rails 4

鉴于这 2 个模型:

class Conversation < ActiveRecord::Base
  has_many :messages, :class_name => 'Message', inverse_of: 'conversation'

  class Entity < Grape::Entity
    expose :id, :title
    expose :messages, :using => 'Message::Entity'
  end
end

class Message < ActiveRecord::Base
  belongs_to :conversation, :class_name => 'Conversation', inverse_of: 'messages'

  class Entity < Grape::Entity
    expose :id, :content
    expose :conversation, :using => 'Conversation::Entity'
  end
end

我需要将实体呈现为 json 包含它们的关联,因此:

这很好用:

get do
  @c = Conversation.find(1)
  present @c, with: Conversation::Entity
end

虽然这不是:

get do
  @m = Message.find(1)
  present @m, with: Message::Entity
end

它在 conversation 上给了我空值:

{"id":1,"content":"#1 Lorem ipsum dolor sit amet","conversation":null}

所以它似乎不适用于 belongs_to 协会。

我需要做什么才能让它发挥作用?

如果是 belongs_to,您需要像这样明确提及 foreign_key

class Message < ActiveRecord::Base
  belongs_to :conversation, :class_name => 'Conversation', inverse_of: 'messages', foreign_key: :conversation_id

  class Entity < Grape::Entity
    expose :id, :content
    expose :conversation, :using => 'Conversation::Entity'
  end
end