You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# Given Models
class Person < ActiveRecord::Base
has_many :spoken_languages
validates :name, :email, :spoken_languages, presence: true
end
class SpokenLanguage < ActiveRecord::Base
belongs_to :person, inverse_of: :spoken_languages
validates :person, :language_code, presence: true
end
# Resource with getters and setter
class PersonResource < JSONAPI::Resource
attributes :name, :email, :spoken_languages
# Getter
def spoken_languages
@model.spoken_languages.pluck(:language_code)
end
# Setter (because spoken_languages needed for creation)
def spoken_languages=(new_spoken_language_codes)
@model.spoken_languages.destroy_all
new_spoken_language_codes.each do |new_lang_code|
@model.spoken_languages.build(language_code: new_lang_code)
end
end
end
When GET /persons is processed, the spoken languages are individually queried from the database for every person in the collection. I was able to optimize the queries by adding this code to PersonResource:
def self.records_for_populate(options = {})
records_base(options).includes(:spoken_languages)
end
Is that the right thing to do here? If yes then you can consider to improve the documentation by including that snippet.
The text was updated successfully, but these errors were encountered:
I followed the docs on flattening a Rails relationship. For completeness, let me copy-paste the code from the docs:
When
GET /persons
is processed, the spoken languages are individually queried from the database for every person in the collection. I was able to optimize the queries by adding this code toPersonResource
:Is that the right thing to do here? If yes then you can consider to improve the documentation by including that snippet.
The text was updated successfully, but these errors were encountered: