简体   繁体   中英

ActiveModel Serializer with has_and_belongs_to_many

I have a model called Event. An Event has_and_belongs_to_many :event_sub_categories and a 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. I tried making the following ActiveModel Serializer:

 class EventSerializer < ActiveModel::Serializer
   attributes :id, :name, :event_sub_categories
 end

but the serializer above doesn't change the json at all. 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:

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

3- in your Event serializer create the method 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM