Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

note on performance when "flattening a Rails relationship" #47

Open
JuliusRapp opened this issue Jan 9, 2020 · 0 comments
Open

note on performance when "flattening a Rails relationship" #47

JuliusRapp opened this issue Jan 9, 2020 · 0 comments

Comments

@JuliusRapp
Copy link

I followed the docs on flattening a Rails relationship. For completeness, let me copy-paste the code from the docs:

# 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant