I'm trying to combine three scopes in one (one scope uses the other two).
I want to get all videos which don't have certain categories and certain tags.
Video
class Video < ActiveRecord::Base
self.primary_key = "id"
has_and_belongs_to_many :categories
has_and_belongs_to_many :tags
scope :with_categories, ->(ids) { joins(:categories).where(categories: {id: ids}) }
scope :excluded_tags, -> { joins(:tags).where(tags: {id: 15}) }
scope :without_categories, ->(ids) { where.not(id: excluded_tags.with_categories(ids) ) }
end
But when I call
#excluded_categories = [15,17,26,32,35,36,37]
#videos = Video.without_categories(#excluded_categories)
I still get video which has tag 15.
The SQL query which server is firing looks like this
SELECT "videos"."video_id" FROM "videos" WHERE ("videos"."id" NOT IN (SELECT "videos"."id" FROM "videos" INNER JOIN "tags_videos" ON "tags_videos"."video_id" = "videos"."id" INNER JOIN "tags" ON "tags"."id" = "tags_videos"."tag_id" INNER JOIN "categories_videos" ON "categories_videos"."video_id" = "videos"."id" INNER JOIN "categories" ON "categories"."id" = "categories_videos"."category_id" WHERE "tags"."id" = $1 AND "categories"."id" IN (15, 17, 26, 32, 35, 36, 37))) [["id", 15]]
Am I doing something wrong?
I think that you must use one scope for excluding categories and a second one for excluding tags and then combine them.
scope :without_categories, ->(ids) { joins(:categories).where.not(categories: {id: ids}) }
scope :without_tags, ->(ids) { joins(:tags).where.not(tags: {id: ids}) }
Then you can use
#excluded_categories = [1,2,3,4]
#excluded_tags = [1,2,3,4,5,6]
#videos = Video.without_categories(#excluded_categories).without_tags(#excluded_tags)
EDIT after comment
After seen the query because chained scopes are using AND the produced query cannot return the desired result. A new approach would be to create one scope only for this purpose.
scope :without_categories_tags, ->
(category_ids, tag_ids) { joins( :categories, :tags).
where('categories.id NOT IN (?) OR tags.id NOT IN (?)', category_ids, tag_ids)}
The you can use
#excluded_categories = [1,2,3,4]
#excluded_tags = [1,2,3,4,5,6]
#videos = Video.without_categories_tags(#excluded_categories,#excluded_tags)
scope :excluded_tags, -> { joins(:tags).where.not(tags: {id: 15}) }
scope :without_categories, ->(ids) { excluded_tags.with_categories(ids) }
Related
It's my DB scheme:
branches
-----------------------------------
id
name:string
active:boolean
..
course_contents
-----------------------------------
id
title:string
show_all_branches:boolean
active:boolean
..
branches_course_contents
-----------------------------
branch_id
course_content_id
And my model files:
class Branch < ApplicationRecord
has_and_belongs_to_many :course_contents
scope :active, -> { where(active: true) }
end
class CourseContent < ApplicationRecord
has_and_belongs_to_many :branches
scope :active, -> { where(active: true) }
scope :show_all_branches, -> { where(show_all_branches: true) }
end
I'm trying to CourseContent.show_all_branches.merge(-> { joins(:branches) }) this command. It returns show_all_branches selected and has relations with branches table. But i need show_all_branches selected or has relations with branches table.
Thanks for helps. I solved this problem and I writing my solution for other peoples. I said actually need to branch's course_contents with show_all_branches selected in the course_contents table. I tried merge method with this CourseContent.show_all_branches.merge(-> { joins(:branches) }) or other many methods with other conditions. Cuz I used to joins/includes method all of my conditions. It's never returns true result for me. And I finally tried left_joins method and that solved my problem here.
My commands here:
#course.course_contents.active.left_joins(:branches).where("course_contents.show_all_branches = ? OR branches_course_contents.branch_id = ?", true, #branch.id)
Its sql result
SELECT "course_contents".* FROM "course_contents" LEFT OUTER JOIN "branches_course_contents" ON "branches_course_contents"."course_content_id" = "course_contents"."id" LEFT OUTER JOIN "branches" ON "branches"."id" = "branches_course_contents"."branch_id" WHERE "course_contents"."course_id" = 3 AND "course_contents"."active" = 't' AND (course_contents.show_all_branches = 't' OR branches_course_contents.branch_id = 1)
and its explain:
CACHE (0.0ms) SELECT "course_contents".* FROM "course_contents" LEFT OUTER JOIN "branches_course_contents" ON "branches_course_contents"."course_content_id" = "course_contents"."id" LEFT OUTER JOIN "branches" ON "branches"."id" = "branches_course_contents"."branch_id" WHERE "course_contents"."course_id" = $1 AND "course_contents"."active" = $2 AND (course_contents.show_all_branches = 't' OR branches_course_contents.branch_id = 1) [["course_id", 3], ["active", true]]
Branch Load (1424.1ms) SELECT "branches".* FROM "branches" WHERE "branches"."active" = $1 AND "branches"."slug" = $2 LIMIT $3 [["active", true], ["slug", "izmir"], ["LIMIT", 1]]
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?
Is it possible, to add condition in join query?
For example I want to build next query:
select * from clients
left join comments on comments.client_id = clients.id and comments.type = 1
Client.joins(:comments).all generates only:
select * from clients
left join comments on comments.client_id = clients.id
PS. Client.joins("LEFT JOIN comments on comments.client_id = clients.id and comment.type = 1") isn't nice.
You can do:
Client.left_outer_joins(:comments)
.where(comments: { id: nil })
.or(Client.left_outer_joins(:comments)
.where.not(comments: { id: nil })
.where(comments: { type: 1 }))
what gives you something equivalent to what you want:
SELECT "clients".*
FROM "clients"
LEFT OUTER JOIN "comments"
ON "comments"."client_id" = "clients"."id"
WHERE "comments"."id" IS NULL
OR ("comments"."id" IS NOT NULL) AND "comments"."type" = 1
UPDATE
Actually, this does not work because rails close the parenthesis leaving outside the evaluation of type.
UPDATE 2
If yours comment types are few and is not probable its values will change, you can solve it with this way:
class Client < ApplicationRecord
has_many :comments
has_many :new_comments, -> { where comments: { type: 1 } }, class_name: Comment
has_many :spam_comments, -> { where comments: { type: 2 } }, class_name: Comment
end
class Comment < ApplicationRecord
belongs_to :client
end
With this new relationships in your model now you can do:
Client.left_joins(:comments)
gives:
SELECT "clients".*
FROM "clients"
LEFT OUTER JOIN "comments"
ON "comments"."client_id" = "clients"."id"
Client.left_joins(:new_comments)
gives:
SELECT "clients".*
FROM "clients"
LEFT OUTER JOIN "comments"
ON "comments"."client_id" = "clients"."id" AND "comments"."type" = ?
/*[["type", 1]]*/
Client.left_joins(:spam_comments)
gives the same query:
SELECT "clients".*
FROM "clients"
LEFT OUTER JOIN "comments"
ON "comments"."client_id" = "clients"."id" AND "comments"."type" = ?
/*[["type", 2]]*/
Client.left_joins(:new_comments).where name: 'Luis'
gives:
SELECT "clients".*
FROM "clients"
LEFT OUTER JOIN "comments"
ON "comments"."client_id" = "clients"."id" AND "comments"."type" = ?
WHERE "clients"."name" = ?
/*[["type", 1], ["name", "Luis"]]*/
NOTE:
I try to use a parameter in the original has_many relationship like...
has_many :comments, -> (t) { where comments: { type: t } }
but this give me an error:
ArgumentError: The association scope 'comments' is instance dependent (the scope block takes an argument). Preloading instance dependent scopes is not supported.
I ended up doing this:
meals_select = Meal.left_outer_joins(:dish_quantities).arel
on_expression = meals_select.source.right.first.right.expr
on_expression.children.push(DishQuantity.arel_table[:date].eq(delivery_date))
on_expression.children.push(DishQuantity.arel_table[:dish_id].eq(Dish.arel_table[:id]))
ON "dish_quantities"."meal_id" = "meals"."id" AND "dish_quantities"."date" = '2022-08-05' AND "dish_quantities"."dish_id" = "dishes"."id"
Client.joins(:comments).where(comments: {type: 1})
Try this
If I have a model called User that has_many :games and games has_many :events- How can I get all the users which do not have any games OR have any games with a suspended event.
Here is what I have tried:
Example:
User class:
scope :with_no_games -> {
joins("LEFT OUTER JOIN games g on g.user_id = users.id").where("games.id IS NULL")
}
scope :with_suspended_games_or_no_games -> {
with_no_games.merge(Game.suspended) # <- this doesn't work
}
Game class:
scope :suspended -> {
joins("INNER JOIN events e ON event.game_id = games.id AND event.name = 'suspended'")
}
If I run User.with_suspended_games_or_no_games I get the following SQL statement:
SELECT \"users\".* FROM \"users\" LEFT OUTER JOIN games ON games.user_id = users.id INNER JOIN events ON events.game_id = games.id AND events.name = 'suspended' WHERE (games.user_id IS NULL)"
Which is not what I am looking for. What am I missing?
I think you are looking for
scope :with_suspended_games_or_no_games -> {
with_no_games.joins(:games).merge(Game.suspended)
}
to see the sql try running the following from a rails console:
User.with_suspended_games_or_no_games.to_sql
bonus
you could also write your scopes like:
User
scope :with_no_games -> { joins(:games).where(games: {id: nil}) }
scope :with_suspended_games_or_no_games -> { joins(:games).with_no_games.merge(Game.suspended) }
Game
scope :suspended -> { joins(:events).where(events: {name: 'suspended'}) }
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.