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

时间:2015-03-12 17:47:22

标签: ruby-on-rails ruby rails-activerecord grape grape-entity

鉴于这两个模型:

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上给我null:

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

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

为了让它发挥作用,我需要做些什么?

1 个答案:

答案 0 :(得分:0)

如果是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