Tom*_*oss 18 json ruby-on-rails active-model-serializers
我正在尝试使用Active Model Serializer构建一些Rails模型的JSON表示,其中一些模型嵌入了其他模型.例如,我有Event和Attendees,Event has_and_belongs_to_many Attendees.
class EventSerializer < ActiveModel::Serializer
attributes :name
has_many :attendees, serializer: AttendeeSerializer
end
class AttendeeSerializer < ActiveModel::Serializer
attributes :name
end
Run Code Online (Sandbox Code Playgroud)
这会导致JSON之类的{ name: 'Event One', attendees: [{ name: 'Alice' }, { name: 'Bob' }] }
.
现在,我想补充与会者对此次活动所说的内容.让我们说,评论belongs_to事件,belongs_to参加者.我想在事件的序列化输出中包含所述注释,因此它会成为{ name: 'Event One', attendees: [{ name: 'Alice', comments: [{ text: 'Event One was great!'}] }, { name: 'Bob', comments: [] }] }
.
我本可以有
class AttendeeSerializer < ActiveModel::Serializer
attributes :name
has_many :comments
end
Run Code Online (Sandbox Code Playgroud)
但这会选择此与会者对所有活动的所有评论 - 而不是我想要的.我想写这个,但是如何找到我正在进行序列化的特定事件?我可以以某种方式访问'父'对象,或者可能将选项传递给has_many序列化程序?
class AttendeeSerializer < ActiveModel::Serializer
attributes :name
has_many :comments
def comments
object.comments.where(event_id: the_event_in_this_context.id)
end
end
Run Code Online (Sandbox Code Playgroud)
这是可以完成的事情,还是我应该以另一种方式为这个特定的用例构建JSON?
apn*_*ing 45
我会手动做事来控制:
class EventSerializer < ActiveModel::Serializer
attributes :name, :attendees
def attendees
object.attendees.map do |attendee|
AttendeeSerializer.new(attendee, scope: scope, root: false, event: object)
end
end
end
class AttendeeSerializer < ActiveModel::Serializer
attributes :name, :comments
def comments
object.comments.where(event_id: @options[:event].id).map do |comment|
CommentSerializer.new(comment, scope: scope, root: false)
end
end
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
21163 次 |
最近记录: |