【问题标题】:Presenting `belongs_to` association via Grape Entity in Rails 4在 Rails 4 中通过 Grape Entity 呈现 `belongs_to` 关联
【发布时间】:2015-03-12 17:47:22
【问题描述】:

鉴于这两个模型:

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 关联。

我需要做什么才能让它工作?

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 噗,我知道我会错过一些简单的事情。反正就是这样。事实上foreign_key 就足够了。非常感谢:)
    • 欢迎您!然后我正在更新我的答案。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    相关资源
    最近更新 更多