How to access joined table attributes in Rails3? - sql

I am having trouble accessing the attributes of a join in Rails3.
There is two models/tables : Place and Address. One place can have many addresses (i.e. a specific street address, a "corner of" address, etc.). For historical reasons, the tables do not follow standard Rails conventions:
class Place < ActiveRecord::Base
set_table_name :PLACE
set_primary_key :PLACE_ID
has_many :addresses, :class_name => "Address", :foreign_key => :PLACE_ID
end
and
class Address < ActiveRecord::Base
set_table_name :ADDRESS
set_primary_key :ADDRESS_ID
belongs_to :place, :foreign_key => "PLACE_ID"
end
I am trying to get all the addresses for one particular place:
pa = Place.joins(:addresses).where(:place_id => 68)
The SQL that is generated looks fine:
pa.to_sql
"SELECT [PLACE].* FROM [PLACE] INNER JOIN [ADDRESS] ON [ADDRESS].[PLACE_ID] = [PLACE].[PLACE_ID] WHERE ([PLACE].[place_id] = 68)"
The returned relation also has the right size, as that particular place has 6 addresses associated with it:
irb(main):050:0> pa.size
=> 6
However, the returned relation pa only contains the attributes of the Place model, it doesn't contain any attributes of the Address model.
Pre Rails3 I used to do a find_by_sql and could access the attributes of the two joined table easily in the returned Hash, however I simply cannot get Rails3 to reveal to me the
attributes from the joined Address table.
I must be missing something very basic here - anyone care to point it out to me ?

You're looking for includes instead of joins. This will do exactly what you want.
pa = Place.includes(:addresses).where(:place_id => 68)
If you want to order by address.street_name in your comment to captaintokyo's answer. You can do then add an order like this:
pa = Place.includes(:addresses).where(:place_id => 68).order(:addresses => :street_name)
The difference between the two includes and joins is that joins will join the supplied models to the produced query for the sake matching in a where clause. As opposed to includes which, in addition to adding joining the model, will also include that model's fields in the select statement.
So to recap:
Place.includes(:addresses).where(:place_id => 68)
produces this:
"SELECT [PLACE].*, [ADDRESS].* FROM [PLACE] INNER JOIN [ADDRESS] ON [ADDRESS].[PLACE_ID] = [PLACE].[PLACE_ID] WHERE ([PLACE].[place_id] = 68)"
while
Place.joins(:addresses).where(:place_id => 68)
produces this:
"SELECT [PLACE].* FROM [PLACE] INNER JOIN [ADDRESS] ON [ADDRESS].[PLACE_ID] = [PLACE].[PLACE_ID] WHERE ([PLACE].[place_id] = 68)"

What you need in arel way is just like
pa = Place.joins(:addresses).where(:place_id => 68).select('PLACE.*, ADDRESS.*')
and then you will get all the attributes in pa for these two tables.
But I am wondering if there is a better design for you:
class Place < ActiveRecord::Base
set_table_name :PLACE
set_primary_key :PLACE_ID
has_many :addresses, :class_name => "Address", :foreign_key => :PLACE_ID
end
class Address < ActiveRecord::Base
set_table_name :ADDRESS
set_primary_key :ADDRESS_ID
belongs_to :place, :foreign_key => "PLACE_ID"
scope :with_place, lambda {|place_id| joins(:place).where(:place_id => place_id).select('ADDRESS.*, PLACE.*')}
end
addresses = Address.with_place(68)
or just use the delegate function if you need to use Place instance at the same time
class Address < ActiveRecord::Base
set_table_name :ADDRESS
set_primary_key :ADDRESS_ID
belongs_to :place, :foreign_key => "PLACE_ID"
delegate :any_place_attribute, :to => :place
end
address = Address.find(x)
address.any_place_attribute #you can access PLACE table attribute now

Related

How to group by attribute but display value of nested attribute?

I've got these models in my Rails 6 application:
class Client < ApplicationRecord
belongs_to :account
has_many :people
end
class Person < ApplicationRecord
belongs_to :client
end
class Payment < ApplicationRecord
belongs_to :client
end
In my SharesController I am trying to generate the total payments for each client and show them as a pie chart:
class SharesController < ApplicationController
def index
#clients = current_account.clients.joins(:payments)
.where(:payments => {:date => #range, :currency => #currency})
.order("sum_payments_#{#part} DESC")
.group("clients.id", "clients.name")
.having("sum_payments_#{#part} > 0")
.sum("payments.#{#part}")
end
end
The problem with this is that it groups by client correctly. However, rather than showing each client's name I want to show the last_name of each client's first nested person.
How can this be done?
Thanks for any help.
You should try to create a join between Client and Person and then use uniq to avoid duplicated clients.
You could try something like this (I'm not sure if this code works but just to make it clearer what I mean)
#clients = current_account.clients.joins(:payments, :people)
.where(:payments => {:date => #range, :currency => #currency})
.order("sum_payments_#{#part} DESC")
.group("clients.id", "people.last_name")
.having("sum_payments_#{#part} > 0")
.sum("payments.#{#part}")

How to write a Rails SQL query for finding an object where all children have an equal value

I've been reading this, but can't make sense of writing it into a Rails scope :
find all parent records where all child records have a given value (but not just some child records)
I have a Course, Section, and Quiz, object :
class Course < ActiveRecord::Base
has_many :course_members
has_many :members, through: :course_members
has_many :sections
has_many :quizzes, through: :sections
end
class Quiz < ActiveRecord::Base
belongs_to :member
belongs_to :section
end
class Section < ActiveRecord::Base
belongs_to :course
has_many :quizzes
end
I'd like to find all courses of a member, where all quizzes related to that course have the attribute completed = true.
So in my Member class, I'd ideally like to write something like :
has_many :completed_courses, -> {
joins(:courses, :quizzes, :sections)
# .select( 'CASE WHEN quizzes.completed = true then 1 end') ??? maybe ???
}, class_name: 'Course'
Haha! But barring that being too complicated. I've been trying to write this simply in the Course would also be fine.
class Member < ActiveRecord::Base
has_many :courses, through: :course_members
has_many :course_members
has_many :completed_courses,
-> { joins(:quizzes).where.not(quizzes: {completed: [false, nil]}) },
through: :course_members,
source: :course
end
If your completed boolean column is NOT NULL, then change [false, nil] above to just simply false
Usage Example
irb(main):002:0> Member.first.completed_courses
Member Load (0.2ms) SELECT "members".* FROM "members" ORDER BY "members"."id" ASC LIMIT 1
Course Load (0.1ms) SELECT "courses".* FROM "courses" INNER JOIN "sections" ON "sections"."course_id" = "courses"."id" INNER JOIN "quizzes" ON "quizzes"."section_id" = "sections"."id" INNER JOIN "course_members" ON "courses"."id" = "course_members"."course_id" WHERE (NOT (("quizzes"."completed" = 'f' OR "quizzes"."completed" IS NULL))) AND "course_members"."member_id" = ? [["member_id", 1]]

Rails 3: has_many through query

I have these three Active Record models:
class Event < ActiveRecord::Base
has_many :event_categories, inverse_of: :event
has_many :categories, through: :event_categories
end
class EventCategory < ActiveRecord::Base
belongs_to :event
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :event_categories
has_many :events, through: :event_categories
end
I think the relations are good.
If I want to know what Events have a Category, for example id=5.. I do:
Category.find(5).events
But, if I want to know all Events for more than one category, for example:
Category.where(:id => [3,5]).events
It isn't working. Any ideas?
Please note, when you do has_many :events in a model, Active Record defines a method of name events for that class.
When you do Category.find(5).events, you get events associated with one object (i.e. Category.find(5)) , however Category.where(:id => [3,5]) returns an array of Category objects, so you can't use events function on an array, Only way to get events for all search results is iterate over them and access them individually, something like following:
all_events = Category.where(:id => [3,5]).inject([]) {|res,cat| res << cat.events}
Above code will do one query per iteration, to avoid this, we can include events, in the first query itself, like following, which will provide result in only one query:
all_events = Category.includes(:events).where(:id => [3,5]).inject([]) {|res,cat| res << cat.events}

Why are individual SELECT queries running when an all-encompassing SELECT already ran? (Rails/ActiveRecord)

I have the following code (note the includes and the .each):
subscribers = []
mailgroup.mailgroup_members.opted_to_receive_email.includes(:roster_contact, :roster_info).each { |m|
subscribers << { :EmailAddress => m.roster_contact.member_email,
:Name => m.roster_contact.member_name,
:CustomFields => [ { :Key => 'gender',
:Value => m.roster_info.gender.present? ? m.roster_info.gender : 'X'
} ]
} if m.roster_contact.member_email.present?
}
subscribers
Correspondingly, I see the following in my logs (i.e. select * from ROSTER_INFO ... IN (...)):
SELECT `ROSTER_INFO`.* FROM `ROSTER_INFO` WHERE `ROSTER_INFO`.`ID` IN ('1450', '1000', '1111')
Yet immediately after that there are select * from ROSTER_INFO for each ID already specified in the IN list of the previous query:
RosterInfo Load (84.8ms) SELECT `ROSTER_INFO`.* FROM `ROSTER_INFO` WHERE `ROSTER_INFO`.`ID` = '1450' LIMIT 1
RosterInfo Load (59.2ms) SELECT `ROSTER_INFO`.* FROM `ROSTER_INFO` WHERE `ROSTER_INFO`.`ID` = '1000' LIMIT 1
RosterInfo Load (56.8ms) SELECT `ROSTER_INFO`.* FROM `ROSTER_INFO` WHERE `ROSTER_INFO`.`ID` = '1111' LIMIT 1
If select * had already been done on ROSTER_INFO on all IDs of interest (IN (...)), why is another select * being done again for each of the same IDs? Doesn't ActiveRecord already know all the ROSTER_INFO columns for each ID?
(Meanwhile, there are no individual queries for ROSTER_CONTACT, yet if I remove :roster_contact from the includes method, then ROSTER_INFO is not queried again, but ROSTER_CONTACT is.)
RosterInfo model (abridged)
class RosterInfo < ActiveRecord::Base
self.primary_key = 'ID'
end
RosterContact model (abridged)
class RosterContact < ActiveRecord::Base
self.primary_key = 'ID'
has_many :mailgroup_members, foreign_key: 'rosterID'
has_many :mailgroups, through: :mailgroup_members
has_one :roster_info, foreign_key: 'ID' # can use this line
#belongs_to :roster_info, foreign_key: 'ID' # or this with no difference
def member_name # I added this method to this
roster_info.member_name # question only *after* having
end # figured out the problem.
end
RosterWeb model (abridged)
class RosterWeb < ActiveRecord::Base
self.primary_key = 'ID'
end
Mailgroup model (abridged)
class Mailgroup < ActiveRecord::Base
self.primary_key = 'ID'
has_many :mailgroup_members, foreign_key: 'mailCatID'
has_one :mailing_list, foreign_key: :legacy_id
end
MailgroupMember model (abridged)
class MailgroupMember < ActiveRecord::Base
self.primary_key = 'ID'
belongs_to :mailgroup, foreign_key: 'mailCatID'
belongs_to :roster_contact, foreign_key: 'rosterID'
belongs_to :roster_info, foreign_key: 'rosterID'
belongs_to :roster_web, foreign_key: 'rosterID'
scope :opted_to_receive_email, joins(:roster_web).where('ROSTER_WEB.receiveEmail=?', 1)
end
The issue turned out to be related to m.roster_contact.member_name -- unfortunately I made member_name a method of roster_contact that itself (indirectly) queried roster_info.member_name. I resolved this by changing the line
:Name => m.roster_contact.member_name,
to directly query roster_info as follows
:Name => m.roster_info.member_name,
I am sorry for the trouble!
I'm going to stick my neck out and say that this is probably an in-flight optimization by your query engine. The 'IN' is typically used to compare large sets of keys, the most efficient way of resolving three keys (assuming ID is the key) would be to retrieve each row by key, as has happened.
class RosterInfo < ActiveRecord::Base
has_one :roster_contact, foreign_key: 'ID'
end
class RosterContact < ActiveRecord::Base
has_one :roster_info, foreign_key: 'ID'
end
I don't know what is the premise for having bi-directional has_one, but I suspect it will turn out badly. Probably change one of them to belongs_to. Do the same for the other bi-directional has_one associations.
Another thing is that you are using 'ID' for the foreign_key column, where the usual practice is roster_contact_id or whichever class you are referencing.
Edit:
On closer examination, RosterInfo, RosterContact, RosterWeb look like separate tables for what should be a single record since they are all having the same set of mutual has_one associations. This is something that should be addressed on the schema level, but right now you should be able to drop the has_one associations from one of the three models to solve your immediate problem.

Ruby ActiveRecord multiple joins through associations

I'd like to convert
SELECT `users`.* FROM `users`
INNER JOIN `memberships`
ON `memberships`.`user_id` = `users`.`id`
INNER JOIN `roles`
ON `roles`.`id` = `memberships`.`role_id`
WHERE `memberships`.`group_id` = 'NUCC' AND (expiration > '2012-07-02')
ORDER BY `roles`.`rank` DESC
Into an ActiveRecord association.
Groups have many members (class User) through memberships. Each membership has a role (role_id) which maps to another table (roles) and subsequently an AR model (Role). Each role has a rank (integer) associated with it.
I'd like to simply sort the members of a group by the memberships-roles-rank.
Untested, probably has typos, but...
class User < ActiveRecord::Base
has_many :memberships
has_many :roles, :through => :memberships, :uniq => true
end
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :role
end
class Role < ActiveRecord::Base
has_many :memberships
has_many :users, :through => :memberships, :uniq => true
end
And then, to sort the users by roles.rank:
q = User.joins(:memberships => :users)
q = q.where(:memberships.group_id => 'NUCC')
q = q.where("expressionn > '2012-07-02'")
q = q.order("roles.rank DESC")
puts q.to_sql
AREL lets you join things up like that pretty easily. For instance, you can keep that going with even further INNER JOINS with syntax similar to:
User.joins(:memberships => { :users => :someothermodel })
Just remember to replicate that structure whenever you need to reference something through the JOIN, or just write your own SQL fragment..