Rails 如何只返回 belongs_to Model 的部分 field

birbird · August 13, 2015 · Last by birbird replied at August 15, 2015 · 1848 hits

每个 Speech 都有一个 author(类型 User),我希望 Speech 的 author 只包含 name 和 picture,而不要把 User 的所有 field 都返回了。 我想到的办法是用自定义 as_json,请问有没有别的办法? 代码如下

class Speech
  include Mongoid::Document
  belongs_to :author, class_name: "User"

  def author_
    author.as_json(only: [:name, :picture])
  end
end

# 我用了 Grape Entity,但 Entity 上好像做不了精简 field 的事
present speeches, with: Entities::Topic
def author
  { name: author.name, picture: author.picture }
end

😃

为什么只要某些字段呢?应用场景是什么?

可以从 query 的时候入手:

belongs_to :author,->{select([:name,:picture])}
expose :name, :pictrue

方法真多啊,感谢你们!@hz_qiuyuanxin @mueven @fresh_fish

You need to Sign in before reply, if you don't have an account, please Sign up first.