Home > Mobile >  Rails where method with array parameter - example from a book, not clear to me
Rails where method with array parameter - example from a book, not clear to me

Time:06-01

I'm reading the book 'Beginning Rails 6 - From Novice to Professional' (awesome book, btw), and I'm on a chapter about Advanced Active Record, great information, but one part of the text is driving me crazy, it works, but I don't get the explanation, could someone please clarify it to me?

As in a regular where method, you can use arrays as parameters. In fact, you can chain finder methods with other named scopes. You define the recent scope to give you articles recently published: first, you use the published named scope, and then you chain to it a where call

To me, the code example isn't exactly what text says (I've tried to find any erratas, with no success):

class Article < ApplicationRecord validates :title, :body, presence: true
belongs_to :user has_and_belongs_to_many :categories has_many :comments

scope :published, -> { where.not(published_at: nil) }
scope :draft, -> { where(published_at: nil) }
scope :recent, -> { where('articles.published_at > ?', 1.week.ago.to_date) }

def long_title
"#{title} - #{published_at}"
end end

I don't see the You define the recent scope to give you articles recently published: first, you use the published named scope, and then you chain to it a where call, plus, can't I just use scope :recent, -> { where('published_at > ?', 1.week.ago.to_date) } instead scope :recent, -> { where('articles.published_at > ?', 1.week.ago.to_date) } removing the articles from the where?

Thanks a lot!

CodePudding user response:

So what the text tries to say are two things. One is that you can use arrays in where and active record understands and translates it properly to SQL. For example Article.where(user_id: [1,2,3]) will find all articles where the user_id is either 1, 2 or 3.

The second thing they try to explain is that you can chain scopes. So in this case, what they try to explain is that you can do this: Article.recent.published or Article.recent.draft

For your last question, yes you can write it like you suggest and it would work :recent, -> { where('published_at > ?', 1.week.ago.to_date) }. The reason they use articles. is to ensure the scope works when you try to chain scopes with joins.

  • Related