[英]ActiveModel Serializer with has_and_belongs_to_many
I have a model called Event. 我有一个名为Event的模型。 An Event has_and_belongs_to_many :event_sub_categories
and a EventSubCategory has_and_belongs_to_many :events
. 事件has_and_belongs_to_many :event_sub_categories
和EventSubCategory has_and_belongs_to_many :events
。 I have the following action: 我有以下行动:
def index
@events = Event.where(begins_at: DateTime.now.beginning_of_day..1.week.from_now).group_by{|e| e.begins_at.beginning_of_day}.to_a.to_json
render json: @events
end
The action returns the data exactly as needed except for one problem, it doesn't have subcategories. 除了一个问题之外,该操作将根据需要完全返回数据,它没有子类别。 I need the json to contain the subcategories. 我需要json来包含子类别。 I tried making the following ActiveModel Serializer: 我尝试制作以下ActiveModel Serializer:
class EventSerializer < ActiveModel::Serializer
attributes :id, :name, :event_sub_categories
end
but the serializer above doesn't change the json at all. 但上面的序列化器根本不会改变json。 How do I fix this? 我该如何解决?
try 尝试
class EventSerializer < ActiveModel::Serializer
attributes :id, :name
has_many :event_sub_categories
end
Try this: 试试这个:
1- In your controller modify the query in a way it includes the event_sub_categories: 1-在您的控制器中,以包含event_sub_categories的方式修改查询:
def index
@events = Event.includes(:event_sub_categories).where(begins_at: DateTime.now.beginning_of_day..1.week.from_now).group_by{|e| e.begins_at.beginning_of_day}.to_a.to_json
render json: @events
end
2- create a Serializer for EventSubCategory model 2-为EventSubCategory模型创建一个Serializer
3- in your Event serializer create the method event_sub_categories 在事件序列化程序中创建方法event_sub_categories
class EventSerializer < ActiveModel::Serializer
attributes :id, :name, :event_sub_categories
def event_sub_categories
object.event_sub_categories.map do |sub_category|
EventSubCategorySerializer.new(sub_category)
end
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.