ruby-on-railsrubyrails-activerecordruby-grapegrape-entity

Presenting `belongs_to` association via Grape Entity in Rails 4


Given these 2 models:

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

I need to present entities as json containing their associations, and so:

This works fine:

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

While this not:

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

It gives me null on conversation:

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

So it looks like it's not working for belongs_to associations.

What i need to do in order to make it work?


Solution

  • In case of belongs_to you need to mention the foreign_key explicitly like this:

    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