【发布时间】:2015-04-14 16:48:27
【问题描述】:
我想在 Active Model Serializer 中使用 pluck 方法进行对象关联:
Post has_many :comments
有没有办法覆盖
has_many :comments
在序列化程序中使用 pluck(:id, :title) 在 cmets 上?
【问题讨论】:
标签: ruby-on-rails active-model-serializers
我想在 Active Model Serializer 中使用 pluck 方法进行对象关联:
Post has_many :comments
有没有办法覆盖
has_many :comments
在序列化程序中使用 pluck(:id, :title) 在 cmets 上?
【问题讨论】:
标签: ruby-on-rails active-model-serializers
您可以使用带有 has_many 的块来扩展您与方法的关联。请参阅评论“使用块扩展您的关联”here。
class Post < ActiveRecord::Base
has_many :comments do
def plucked()
select("id, title")
end
end
end
或其他方法,从同一链接可以,在从数据库中获取 comments 时使用您的自定义 sql 查询:
has_many :comments, :class_name => 'Comment', :finder_sql => %q(
SELECT id, title
FROM comments
WHERE post_id = #{id}
)
在railsdocumentation中,显示,有一个选项:select,也可以用于这个目的。
【讨论】:
在这种情况下我通常会做什么,我有两个不同的序列化程序CommentSerializer 和CommentInfoSerializer。所以CommentInfoSerializer 只包含我想在其父资源的嵌入属性中响应的最小属性。
class CommentSerializer < ActiveModel::Serializer
attributes :id, :title, :body
end
class CommentInfoSerializer < ActiveModel::Serializer
attributes :id, :title
end
class PostSerializer < ActiveModel::Serializer
has_many :comments, serializer: CommentInfoSerializer
end
【讨论】: