ActiveRecord select add count - ruby-on-rails

In my ActiveRecord query, I need to provide this info in the select method:
(SELECT count(*) from likes where likes.spentit_id = spentits.id) as like_count,
(SELECT count(*) from comments where comments.spentit_id = spentits.id) as comment_count
Of course, I pass pass these two as string to the .select() part, but I am wondering what's the proper/alternative way of doing this?
Here's the complete query I am trying to call:
SELECT DISTINCT
spentits.*,
username,
(SELECT count(*) from likes where likes.spentit_id = spentits.id) as like_count,
(SELECT count(*) from comments where comments.spentit_id = spentits.id) as comment_count,
(SELECT count(*) from wishlist_items where wishlist_items.spentit_id = spentits.id) as wishlist_count,
(case when likes.id is null then 0 else 1 end) as is_liked_by_me,
(case when wishlist_items.id is null then 0 else 1 end) as is_wishlisted_by_me,
(case when comments.id is null then 0 else 1 end) as is_commented_by_me
FROM spentits
LEFT JOIN users ON users.id = spentits.user_id
LEFT JOIN likes ON likes.user_id = 9 AND likes.spentit_id = spentits.id
LEFT JOIN wishlist_items ON wishlist_items.user_id = 9 AND wishlist_items.spentit_id = spentits.id
LEFT JOIN comments ON comments.user_id = 9 AND comments.spentit_id = spentits.id
WHERE spentits.user_id IN
(SELECT follows.following_id
FROM follows
WHERE follows.follower_id = 9 AND follows.accepted = 1)
ORDER BY id DESC LIMIT 15 OFFSET 0;
All the tables here have their respective ActiveRecord object. Just really confused how to convert this query into 'activerecord'/rails way with writing least amount of SQL. The '9' user_id is suppose to be a parameter.
Update:
Ok so here's what I did inmean time, it's much better than raw SQL statement, but it still looks ugly to me:
class Spentit < ActiveRecord::Base
belongs_to :user
has_many :likes
has_many :wishlist_items
has_many :comments
scope :include_author_info, lambda {
joins([:user]).
select("username").
select("users.photo_uri as user_photo_uri").
select("spentits.*")
}
scope :include_counts, lambda {
select("(SELECT count(*) from likes where likes.spentit_id = spentits.id) as like_count").
select("(SELECT count(*) from comments where comments.spentit_id = spentits.id) as comment_count").
select("(SELECT count(*) from wishlist_items where wishlist_items.spentit_id = spentits.id) as wishlist_items_count").
select("spentits.*")
}
end
Using these scope methods, I can do:
Spentit.where(:id => 7520).include_counts.include_author_info.customize_for_user(45)
A bit about the classes. A User has many Spentits. A Spentit has many comments, likes and comments.

Ok, you're "doing it wrong", a little bit. Rather than
scope :include_counts, lambda {
select("(SELECT count(*) from likes where likes.spentit_id = spentits.id) as like_count").
select("(SELECT count(*) from comments where comments.spentit_id = spentits.id) as comment_count").
select("(SELECT count(*) from wishlist_items where wishlist_items.spentit_id = spentits.id) as wishlist_items_count").
select("spentits.*")
}
do
Spentit.find(7520).likes.count
Spentit.find(7520).wishlist_items.count
Spentit.find(7520).comments.count
Instead of
scope :include_author_info, lambda {
joins([:user]).
select("username").
select("users.photo_uri as user_photo_uri").
select("spentits.*")
}
do
Spentit.find(7520).user.username
Spentit.find(7520).user.photo_uri
Also, you can define scopes within the referenced models, and use those:
class Follow < ActiveRecord::Base
belongs_to :follower, :class_name => "User"
belongs_to :following, :class_name => "User"
scope :accepted, lambda{ where(:accepted => 1) }
end
Spentits.where(:user => Follow.where(:follower => User.find(9)).accepted)
Now, maybe you also do:
class Spentit
def to_hash
hash = self.attributes
hash[:like_count] = self.like.count
# ...
end
end
but you don't need to do anything fancy to get those counts "under normal circumstances", you already have them.
Note, however, you'll probably also want to do eager loading, which you can apparently make as part of the default scope, or you'll do a lot more queries than you need.

Related

Scope Order by Count with Conditions Rails

I have a model Category that has_many Pendencies. I would like to create a scope that order the categories by the amount of Pendencies that has active = true without excluding active = false.
What I have so far is:
scope :order_by_pendencies, -> { left_joins(:pendencies).group(:id).order('COUNT(pendencies.id) DESC')}
This will order it by number of pendencies, but I want to order by pendencies that has active = true.
Another try was:
scope :order_by_pendencies, -> { left_joins(:pendencies).group(:id).where('pendencies.active = ?', true).order('COUNT(pendencies.id) DESC')}
This will order by number of pendencies that has pendencies.active = true, but will exclude the pendencies.active = false.
Thank you for your help.
I guess you want to sort by the amount of active pendencies without ignoring categories that have no active pendencies.
That would be something like:
scope :order_by_pendencies, -> {
active_count_q = Pendency.
group(:category_id).
where(active: true).
select(:category_id, "COUNT(*) AS count")
joins("LEFT JOIN (#{active_count_q.to_sql}) AS ac ON ac.category_id = id").
order("ac.count DESC")
}
The equivalent SQL query:
SELECT *, ac.count
FROM categories
LEFT JOIN (
SELECT category_id, COUNT(*) AS count
FROM pendencies
GROUP BY category_id
WHERE active = true
) AS ac ON ac.category_id = id
ORDER BY ac.count DESC
Note that if there are no active pendencies for a category, the count will be null and will be added to the end of the list.
A similar subquery could be added to sort additionally by the total amount of pendencies...
C# answer as requested:
method() {
....OrderBy((category) => category.Count(pendencies.Where((pendency) => pendency.Active))
}
Or in straight SQL:
SELECT category.id, ..., ActivePendnecies
FROM (SELECT category.id, ..., count(pendency) ActivePendnecies
FROM category
LEFT JOIN pendency ON category.id = pendency.id AND pendnecy.Active = 1
GROUP BY category.id, ...) P
ORDER BY ActivePendnecies;
We have to output ActivePendnecies in SQL even if the code will throw it out because otherwise the optimizer is within its rights to throw out the ORDER BY.
For now I developed the following (it's working, but I believe that it's not the best way):
scope :order_by_pendencies, -> { scoped = Category.left_joins(:pendencies)
.group(:id)
.order('COUNT(pendencies.id) DESC')
.where('pendencies.active = ?', true)
all = Category.all
(scoped + all).uniq}

Merge ActiveRecord_Relation

In model Banner
belongs_to :segment
belongs_to :basic_component
has_many :state_banners, dependent: :destroy
has_many :states, through: :state_banners
scope :banner_have_zero_cities, lambda { includes(state_banners: :state_banner_cities).where(state_banner_cities: {state_banner_id: nil}) }
scope :banner_by_state, lambda { |state_id| where("state_banners.state_id = ?", state_id) }
scope :banner_by_city, lambda { |city_id| joins(state_banners: :state_banner_cities).where("state_banner_cities.city_id = ?", city_id) }
In controller
def scoped_collection
#banners_cities = Banner.banner_by_city(city_id)
#banners_states =Banner.banner_by_state(city.state_id).banner_have_zero_cities
#banners = #banners_cities.concat(#banners_states)
return #banners.joins(:basic_component)
end
#banners_states.size
=> 1
#banners_cities.size
=> 2
#banners_states.merge(#banners_cities)
SQL (0.2ms) SELECT DISTINCT banners.id FROM banners INNER JOIN state_banners ON state_banners.banner_id = banners.id INNER JOIN state_banner_cities ON state_banner_cities.state_banner_id = state_banners.id WHERE (state_banners.state_id = 3) AND state_banner_cities.state_banner_id IS NULL AND (state_banner_cities.city_id = '260') LIMIT 25 OFFSET 0
=> []
I need 3
i try concat
#banners = #banners_cities.concat(#banners_states)
#banners.size => 3
but
#banners.joins(:basic_component).order("basic_component.order asc").size => 2
CACHE (0.0ms) SELECT COUNT(count_column) FROM (SELECT 1 AS count_column FROM banners INNER JOIN state_banners ON state_banners.banner_id = banners.id INNER JOIN state_banner_cities ON state_banner_cities.state_banner_id = state_banners.id INNER JOIN basic_components ON basic_components.id = banners.basic_component_id WHERE (state_banner_cities.city_id = '260') LIMIT 25 OFFSET 0) subquery_for_count
:(, help
Your post is kind of hard to follow, but try .limit(3) at the end of the query?

Change a instance method to a has_many on Rails

has_many.rb
has_many :child_attendances, -> (attendance) {
includes(:activity).references(:activity).
where(activities: {parent_activity_id: attendance.activity_id}).
where(
Attendance.arel_table.grouping(
Attendance.arel_table[:attendant_id].eq(attendance.attendant_id).
and(Attendance.arel_table[:attendant_type].eq(attendance.attendant_type))
).
or(Attendance.arel_table[:tag_code].eq(attendance.tag_code))
)
}, class_name: 'Attendance', dependent: :destroy
methods.rb
def self.child_attendances(attendance)
includes(:activity).references(:activity).
where(activities: {parent_activity_id: attendance.activity_id}).
where(
Attendance.arel_table.grouping(
Attendance.arel_table[:attendant_id].eq(attendance.attendant_id).
and(Attendance.arel_table[:attendant_type].eq(attendance.attendant_type))
).
or(Attendance.arel_table[:tag_code].eq(attendance.tag_code))
)
end
def child_attendances
self.class.child_attendances(self)
end
When using has_many.rb
-- attendance.child_attendances.to_sql
SELECT "attendances"."id" AS t0_r0 FROM "attendances" LEFT OUTER JOIN "activities" ON "activities"."id" = "attendances"."activity_id" WHERE "activities"."parent_activity_id" = 654 AND (("attendances"."attendant_id" IS NULL AND "attendances"."attendant_type" IS NULL) OR "attendances"."tag_code" = '123456789') AND "attendances"."attendance_id" = 164513
It appends "attendances"."attendance_id" = 164513, and attendance_id is not a valid column for Attendance.
When using methods.rb
-- attendance.child_attendances.to_sql
SELECT "attendances"."id" AS t0_r0 FROM "attendances" LEFT OUTER JOIN "activities" ON "activities"."id" = "attendances"."activity_id" WHERE "activities"."parent_activity_id" = $1 AND (("attendances"."attendant_id" IS NULL AND "attendances"."attendant_type" IS NULL) OR "attendances"."tag_code" = '123456789') [["parent_activity_id", 654]]
How to make the other snippet into a has_many? Rails seems to always look for a primary_key and foreign_key to make the join, when using has_many.
According to https://stackoverflow.com/a/34444220 what I was trying to do does not make sense to be built using has_many, so I'm sticking with an instance method.
def child_attendances
self.class.includes(:activity).references(:activity).
where(activities: {parent_activity_id: activity_id}).
where(
Attendance.arel_table.grouping(
Attendance.arel_table[:attendant_id].eq(attendant_id).
and(Attendance.arel_table[:attendant_type].eq(attendant_type))
).
or(Attendance.arel_table[:tag_code].eq(tag_code))
)
end

Rails: Postgresql where with multiple conditions with join (polymorphic)

Hi guys here is my code:
class Tailor < ActiveRecord::Base
has_many :tailor_items
has_many :order_items
[:collars, :sexes, :sleeves].each do |attribute|
has_many attribute, through: :tailor_items, source: :item, source_type: attribute.to_s.classify
end
end
class TailorItem < ActiveRecord::Base
belongs_to :tailor
belongs_to :item, polymorphic: true
end
class Collar < ActiveRecord::Base
end
What I need to do is this:
For a given shirt I need to select a tailor. A shirt can have a collar, male/female or a certain type of sleeve. Some tailors can make all collars but only a few sleeves, others can make only male stuff, etc.
The priority doesnt matter for this example. The idea is that I end up with 1 tailor.
I tried this:
tailors = Tailor.joins(:tailor_items).where("(item_id = ? and item_type = ?)",1,"Collar")
if tailors.count > 1
tailors.where("(item_id = ? and item_type = ?)",2,"Sleeve")
if tailors.count > 1
# and so forth.
end
end
But I never get a row back.
If I say:
Tailor.find(1).tailor_items
I get two results (sudo code for simplicity)
<id: 1, item_type: "Collar"><id:2, item_type:"Sleeve">
and for second tailor:
Tailor.find(2).tailor_items
I get two results (sudo code for simplicity)
<id: 1, item_type: "Collar"><id:3, item_type:"Sleeve">
but when I try to chain them in the query its no worky...
Not even if I put it all in one where:
Tailor.where("(item_id = 1 and item_type = 'Collar') and (item_id = 2 and item_type = 'Sleeve')")
I still get 0 results.
Tailor.where("item_id = 1 and item_type = 'Collar'") returns: Tailor #1
Tailor.where("item_id = 2 and item_type = 'Sleeve'") returns: Tailor #1
but together they return nothing.
Tailor Load (0.0ms) SELECT "tailors".* FROM "tailors" INNER
JOIN "tailor_items" ON "tailor_items"."tailor_id" = "tailors"."id" WHERE ((tailo
r_items.item_id = 1 and tailor_items.item_type = 'Collar') and (tailor_items.ite
m_id = 2 and tailor_items.item_type = 'Sleeve'))
I am confused..
Thanks for your help.
I run:
Win XP
Postgresql
Rails 3.2.2
PS: The only thing missing to make this complete after a polymorphic join is a bit of XML. :P Otherwise its just not enterprise-y enough..
EDIT:
Implementing Rob di Marcos scope, I get this SQL:
SELECT "tailors".* FROM "tailors" WHERE
(EXISTS(SELECT * FROM tailor_items WHERE tailor_items.item_id = 1 and tailor_items.item_type = 'Collar'))
AND (exists(select * from tailor_items where tailor_items.item_id = 2 and tailor_items.item_type = 'Sleeve'))
This returns
2 tailors instead of only tailor 1 who can do both (while tailor 2 cant do sleeve #2)
The problem is that the where needs to match on two rows. I generally will use sub-queries to test for this. So something like
Tailor.where("exists (select 'x' from tailor_items where
tailor_id = tailors.id and tailor_items.item_id = ? and
tailor_items.item_type=?)", 1, 'Collar').
where("exists (select 'x' from tailor_items where
tailor_id = tailors.id and tailor_items.item_id = ? and
tailor_items.item_type=?)", 2, 'Sleeve')
In this example, I have one sub-query for each tailor item I am looking for. I could easily make this a scope on Tailor like:
class Tailor
# ....
scope :with_item, lambda{ |item_id, item_type |
where("exists (select 'x' from tailor_items where
tailor_id = tailors.id and tailor_items.item_id = ? and
tailor_items.item_type=?)", item_id, item_type)
}
and then be able to chain my Tailor request
Tailor.with_item(1, 'Collar').with_item(2, 'Sleeve')

How can I write the most efficient scope for asking only those parent objects which have some certain child objects

I have:
class Evaluation < ActiveRecord::Base
has_many :scores
end
class Score < ActiveRecord::Base
scope :for_disability_and_score,
lambda { |disability, score|
where('total_score >= ? AND name = ?', score, disability)
}
end
The scores table has a total_score field and a name field.
How can i write a scope to ask for only those evaluations which have a Score with name 'vision' and total_score of 2 and they have another Score with name 'hearing' and total_score of 3.
And how can all this be generalized to ask for those evaluations which have n scores with my parameters?
In raw sql it would be like:
I managed to do it in raw sql:
sql = %q-SELECT "evaluations".*
FROM "evaluations"
INNER JOIN "scores" AS s1 ON "s1"."evaluation_id" = "evaluations"."id"
INNER JOIN "target_disabilities" AS t1 ON "t1"."id" = "s1"."target_disability_id"
INNER JOIN "scores" AS s2 ON "s2"."evaluation_id" = "evaluations"."id"
INNER JOIN "target_disabilities" AS t2 ON "t2"."id" = "s2"."target_disability_id"
WHERE "t1"."name" = 'vision' AND (s1.total_score >= 1)
AND "t2"."name" = 'hearing' AND (s2.total_score >= 2)-
Here the point is to repeat this:
INNER JOIN "scores" AS s1 ON "s1"."evaluation_id" = "evaluations"."id"
and this (by replacing s1 to s2 and s3 and so forth):
WHERE (s1.total_score >= 1)
But it should be a rails way of doing this... :) Hopefully
Try this:
scope :by_scores, lambda do |params|
if params.is_a? Hash
query = joins(:scores)
params.each_pair do |name, score|
query = query.where( 'scores.total_score >= ? AND scores.name = ?', score, name)
end
query
end
end
Then call like this:
Evaluation.by_scores 'vision' => 2, 'hearing' => 3

Resources