How to use Rails 3 scope to filter on habtm join table where the associated records don't exist? - activerecord

I have an Author model which habtm :feeds. Using Rails 3 want to setup a scope that finds all authors that have no associated feeds.
class Author < ActiveRecord::Base
has_and_belongs_to_many :feeds
scope :without_feed, joins(:feeds).where("authors_feeds.feed_id is null")
end
...doesn't seem to work. It feels like a simple thing. What am I missing here?

To my knowledge ActiveRecord/Arel do not have a means of defining outer joins. So you'll have to write a bit more SQL than normal. Something like this should do the trick:
scope :without_feed, joins('left outer join authors_feeds on authors.id=authors_feeds.author_id').where('authors_feeds.feed_id is null')
I am of course guessing at your table names and foreign keys. But that should give you the picture.

In Rails >= 5, you can do it like this:
scope :without_feed, -> {
left_outer_joins(:feeds)
.where(authors_feeds: { author_id: nil })
}
scope :with_feed, -> {
left_outer_joins(:feeds)
.where.not(authors_feeds: { author_id: nil })
}

Related

Rails 5 ActiveRecord - combine OR adn AND clauses

I can't figure out the right syntax to use when including several models and using AND or OR clauses.
For example, there Shop model that has_one relation with Address model and belongs_to with Country.
How for example add OR to the below query:
Shop.includes(:address, :country)
Trying like this:
Shop.includes(:address, :country).where('countries.code'=> 'FR').and('counties.updated_at > ?', Date.today.days_ago(7))
raises the error:
NoMethodError: undefined method `and' for #<Shop::ActiveRecord_Relation:0x00007fb90d0ea3f8>
I found this thread at SO, but in this case, I have to repeat the same where clause before each OR statement? - looks not so DRY :(
What am I missing ?
Don't kick yourself... you don't need to use and at all, just string another where in:
Shop.includes(:address, :country).where('countries.code'=> 'FR').where('counties.updated_at > ?', Date.today.days_ago(7))
There is a better solution if you need to add multiple OR clause to AND clause. To get around it, there is arel_table method that can be used as follows.
Let's say we have the following models
Shop -> has_one :address
Shop -> belongs_to :country
and we would like to find all the shops by country code and address updated_at or country updated_at should be greater then a date you pass in:
some_date = Date.today
countries = Country.arel_table
addresses = Address.arel_table
# creating a predicate using arel tables
multi_table_predicate = countries[:updated_at].gt(some_date).or(addresses[:updated_at].gt(some_date))
# building the query
shops = Shop.includes(:address, :country).where(countries: {code: 'FR'}).where(multi_table_predicate)
This will execute a LEFT OUTER JOIN and here is where clause:
WHERE "countries"."code" = $1 AND ("countries"."updated_at" > '2019-03-12' OR "addresses"."updated_at" > '2019-03-12')
Sure, you can chain more tables and multiply OR conditions if you want.
Hope this helps.

Composing ActiveRecord scopes with selects

Unfortunately, ActiveRecord's select replaces the existing SELECT clause instead of adding to it, so I can't compose queries. Does anyone have a workaround?
Example model:
class Story
scope :recent, -> { where("created_at >= ?", 1.month.ago) }
# deliberately simple examples, please don't get distracted memoizing, etc.
scope :with_net_score, -> { select("`stories`.*, (upvotes - downvotes) as net_score" }
scope :with_recent, -> { select("`stories.*, greatest(updated_at, last_vote_at) as recent") }
end
So while I can compose Story.recent.with_net_score, Story.with_net_score.with_recent fails. And both with_net_score and with_recent fail when Story comes after a join to an association.
How would you rewrite with_net_score so that it adds to the fields selected instead of replcaing them and can be composed with with_recent and joins?
Adding the author's own solution to this:
class ApplicationRecord < ActiveRecord::Base
scope :select_fix, -> { select(self.arel_table.project(Arel.star)) }
end
https://github.com/lobsters/lobsters/blob/master/app/models/application_record.rb

Creating a scope on an ActiveRecord Model

I have a ActiveRecord model called Panda with a column called variant, which can consist of values like ‘bam-abc’, ‘bam-123’, ‘boo-abc’ and ‘boo-123’ I want to create a scope which selects all records where the variant starts with ‘boo’.
In the console, I can select those records (starting with ‘boo') with the following:
Panda.select{|p| p.variant.starts_with? 'boo'}
Is there a way to turn that into a scope on the Panda class? I need to be able to do a 'to_sql' on the scope for my RSpec tests.
You'd want to use a scope that sends a LIKE into the database, something like:
scope :boos, -> { where('pandas.variants like ?', 'boo%') }
or equivalently, use a class method:
def self.boos
where('pandas.variants like ?', 'boo%')
end
Then you can say things like:
Panda.boos.where(...)
Panda.where(...).boos
Panda.boos.where(...).to_sql
Panda.where(...).boos.to_sql
You only need to use the pandas prefix on the column name if you think you'll be doing JOINs with other tables that might leave the variant name ambiguous. If you'll never be doing JOINs or you'll only ever have one variant column in your database then you could use one of:
scope :boos, -> { where('variants like ?', 'boo%') }
def self.boos
where('variants like ?', 'boo%')
end
Add the line below to the Panda class
scope :boo, -> { where('variant LIKE ?', 'boo%') }
You can then use Panda.boo to get all the records with variant starting with boo. Panda.boo.to_sql will give you the sql

don't understand complex Ruby code

I'm currently reading Rails 3 In Action. There is code that I was wondering if someone could explain to me. I'm having a hard time understanding it:
scope :readable_by, lambda { |user| joins(:permissions).where(permissions: { action: "view", user_id: user.id })}
thanks,
mike
It's called a Rails scope. It essentially creates a class method called .readable_by(user) that does a SQL join on the permissions table and returns records where the action column value is "view" and the user_id column value equals user.id.
It could be used like so (assuming it's defined in the Comments model):
readable_comments = Comments.readable_by(current_user)
A simple scope that does nothing is this:
scope :my_scope_name, lambda {}
A scope that accepts a parameter is this:
scope :my_scope_name, lambda { |my_parameter| }
And then the above scope uses some ActiveRecord finder methods, specifically joins and where.

Rails 3 Query: How to get most viewed products/articles/whatever?

I always wondered how to query and get results that doesn't fit in a model. Similar how it's done using LINQ and projecting into anonymous objects.
So here's the simple schema:
# Product.rb
class Product < ActiveRecord::Base
has_many :product_views
# attributes: id, name, description, created_at, updated_at
end
# ProductView.rb
class ProductView < ActiveRecord::Base
belongs_to :product
# attributes: id, product_id, request_ip, created_at, updated_at
end
Basically I need to get a list of Products (preferably just id and name) along with the count of views it had. Obviously ordered by view count desc.
This is the SQL I want to get:
select
p.id,
p.name,
count(pv.product_id) as views
from
product_views pv
inner join
products p on pv.product_id = p.id
group by
pv.product_id
order by
count(product_id) desc
I tried the following and similar, but I'm getting ProductView objects, and I would like to get just an array or whatever.
ProductView.includes(:product)
.group('product_id')
.select("products.id, products.name, count(product_id)")
This kind of thing are trivial using plain SQL or LINQ, but I find myself stucked with this kind of queries in Rails. Maybe I'm not thinking in the famous 'rails way', maybe I'm missing something obvious.
So how do you do this kind of queries in Rails 3, and specifically this one? Any suggestions to improve the way I'm doing this are welcome.
Thank you
You can use Arel to do what you're looking for:
products = Product.arel_table
product_views = ProductView.arel_table
# expanded for readability:
sql = products.join(product_views)
.on(product_views[:product_id].eq(product[:id]))
.group(product_views[:product_id])
.order('views DESC')
.project(products[:id],
products[:name],
product_views[:id].count.as('views'))
products_with_views = Product.connection.select_all(sql.to_sql) # or select_rows to just get the values
Yes, it is long, but Arel is a very smart way to deal with creating complex queries that can be reused regardless of the database type.
Within a class method in the Product class:
Product.includes(:product_views).all.map { |p| [p.id, p.name, p.product_views.size] }
Then sort it however you want.
I don't know if there's a way to do it using your models. I would probably resort to:
Product.connection.select_rows(sql)
Which will give you an array of arrays. You can use select_all if you'd rather have an array of hashes.
Try this:
#product = Product.find(#product_id)
#product_views = #product.product_views.count
(Source - http://ar.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html#M000292)
Hope this helps!

Resources