[英]Rails 4: ActiveModelSerializer how to include only those records which are approved?
In my Rails 4.2 API, I'm using active model serializers for constructing json response. 在我的Rails 4.2 API中,我正在使用活动模型序列化程序来构造json响应。 Suppose Post
is a model and it has many comments
and I only want to include comments which are approved/published. 假设Post
是一个模型,并且有很多comments
,我只想包含已批准/发布的评论。 I'm using a scope called approved
which gives approved comments. 我正在使用一个称为approved
的范围,它给出了认可的评论。
JSON response for post includes all comments, how do I include records which are approved and not everything. 发布的JSON响应包含所有注释,我如何包含已批准的记录,而不是所有记录。 How do I construct Post serializer for that. 我该如何构造Post序列化程序。
class PostSerializer < ActiveModel::Serializer
attributes :name, :body
has_many :comments
end
class PostSerializer < ActiveModel::Serializer
attributes :name, :body
has_many :comments
def comments
object.comments.where( status: 'approved' )
end
end
See Active Model Serializers - overriding association methods 请参阅活动模型序列化器-覆盖关联方法
Overriding associations in your serializer will work. 序列化程序中的覆盖关联将起作用。 In serializer just override with this method 在序列化器中只需使用此方法覆盖
def comments
#Your comments filtering
end
If that doesn't work then that has got to be some issue with your version of serializer. 如果那不起作用,那一定是您的序列化程序版本有问题。 Look at this issue for more details and workarounds. 请查看此问题以获取更多详细信息和解决方法。 https://github.com/rails-api/active_model_serializers/issues/267 https://github.com/rails-api/active_model_serializers/issues/267
Check this out too. 也检查一下。 How do I select which attributes I want for active model serializers relationships 如何为活动模型序列化程序关系选择所需的属性
class PostSerializer < ActiveModel::Serializer
attributes :name, :body
has_many :approved_comments, -> { where status: 'approved' }, class_name: 'Comment'
end
PostSerializer.includes(:approved_comments)
Scoping with the approved_comments
. 范围approved_comments
。 Fetching only the comments with the status of approved
. 仅获取状态为approved
的评论。 Got the concept from this http://apidock.com/rails/ActiveRecord/Associations/ClassMethods 从http://apidock.com/rails/ActiveRecord/Associations/ClassMethods获得了概念
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.