【发布时间】:2017-11-16 12:53:24
【问题描述】:
例如,如果我有这些关联的模型
class User
has_many :posts
has_many :comments
def posts_has_comments_in_certain_day(day)
posts.joins(:comments).where(comments: { created_at: day })
end
end
class Post
has_many :comments
belongs_to :user
def comments_in_certain_day(day)
Comment.where(created_at: day, post_id: id)
end
end
class Comment
belongs_to :user
belongs_to :post
end
现在我希望活动模型序列化程序让我所有用户在某一天发布包含 cmets 的帖子,也包括这些 cmets。
我试过了,但我能得到的只是用户在某天发布了包含 cmets 的帖子..但我也无法包含 cmets。
我就是这么做的
class UserSerializer < ActiveModel::Serializer
attributes :id, :name, :day_posts
def day_posts
object.posts_has_comments_in_certain_day(day)
end
end
这工作正常 但是当我尝试包含 cmets 时! ..
class UserSerializer < ActiveModel::Serializer
attributes :id, :name, :day_posts
def day_posts
object.posts_has_comments_in_certain_day(day).map do |post|
PostSerializer.new(
post,
day: instance_options[:day]
)
end
end
class PostSerializer < ActiveModel::Serializer
attributes :id, :body, :day_comments
def day_comments
object.comments_in_certain_day(day)
end
end
这不起作用..有人可以帮我吗?
【问题讨论】:
标签: ruby-on-rails active-model-serializers