ruby - Join type in ActiveRecord has_one Relationship -
just getting started activerecord (in sinatra app). trying port existing queries ar getting little stuck.
if have has_one relation users , profiles (using legacy tables unfortunately)
class user < activerecord::base self.table_name = "systemusers" self.primary_key = "user_id" has_one :profile, class_name: 'profile', foreign_key: 'profile_user_id' end class profile < activerecord::base self.table_name = "systemuserprofiles" self.primary_key = "profile_id" belongs_to :user, class_name: "user", foreign_key: 'user_id' end
if want query users profile using inner join user_age field profiles using 1 query can it?
for example (just added .first reduce code looping through users profiles)
user = user.all(:joins => :profile).first user.profile.user_age
gives me correct data , uses inner join first query issues second query profile data
it gives depreciated warning , suggests use load, tried won't use inner join.
similar case with
user = user.joins(:profile).first user.profile.user_age
i inner join query each user row.
i have tried includes
user = user.includes(:profile).first user.profile.user_age
this lazy loads profile , reduce number of queries in loop, think pull users without profile too
i tried reference
user = user.includes(:profile).references(:profile).first user.profile.user_age
this gives me correct data , reduces queries 1 uses left join
i have not quite grasped , trying achieve thats not do-able, figured might either need use includes , check nil profiles inside loop or use joins , accept additional query each row.
thought i'd check incase missing obvious.
cheers
pat.
profile should have 1 user. so, profile.first.user_age
first user profile. going user approach did,
user.find { |u| u.profile }.profile.user_age
user.find { |u| u.profile }
returns first user true
value.
to query user profiles , user_ages. assuming profiles has user_id , should case.
profile.pluck(:user_age)
this checks presence of user_id if save profiles without user id. where.not
new feature in activerecord, check version.
profile.where.not(user_id: nil).pluck(:user_age)
Comments
Post a Comment