ruby on rails - ActiveRecord Eager Load model that isn't belongs_to -
i'm running issue n+1 queries , want eager load relationship, except i'm having trouble defining relationship. it's complicated, haha, hear me out.
i have 2 models.
class pokemon < activerecord::base belongs_to :pokemon_detail, primary_key: "level", foreign_key: "level" end class pokemondetail < activerecord::base has_one :pokemons, primary_ley: "level", foreign_key: "level" end
let's say, have following record:
<pokemon id: 1, name: "squirtle", level: 1>
which correspond following pokemondetail
<pokemondetail id: 1, name: "squirtle", level: 1, health: 150>
and can eager loaded pokemon.all.includes(:pokemon_detail)
, however, want eager load information 1 level higher.
<pokemondetail id: 2, name: "squirtle", level: 2, health: 300>
i find information 1 level higher following method within pokemon
model.
def next_level_info pokemondetail.where(level: self.level + 1) end
but isn't eager loaded. ideas?
refactor schema first, make more sense:
pokemons { current_level_value, name } pokemon_levels {value, pokemon_id (foreign key), health }
redefine models this:
class pokemonlevel < activerecord::base belongs_to :pokemon end class pokemon < activerecord::base has_many :pokemon_levels has_one :current_pokemon_level, -> { joins(:pokemon).where('pokemons.current_level_value = pokemon_levels.value') }, foreign_key: :pokemon_id, class_name: 'pokemonlevel' has_one :next_pokemon_level, -> { joins(:pokemon).where('pokemons.current_level_value + 1 = pokemon_levels.value') }, foreign_key: :pokemon_id, class_name: 'pokemonlevel' end
simply use eg:
pokemon.includes(:current_pokemon_level, :next_pokemon_level).find(123)
i use pokemonlevel
instead of pokemondetail
, because clearer me
Comments
Post a Comment