Hacker News new | ask | show | jobs
by pqdbr 1736 days ago
Great article. By the way, ActiveRecord's #merge is golden, and I'm under the impression it's not as mainstream as it should be.

I use it extensively to avoid duplicating scope code.

For instance:

class Listing

   scope :active, -> { where("expired_at > ?", Date.current).where.not(suspended: true) }
end

class User

  has_many :listings
end

So instead of doing this (which is terrible):

user.joins(:listings).distinct.where("listings.expired_at > ? AND listings.suspended != FALSE", Date.current)

You can simply:

user.joins(:listings).distinct.merge(Listing.active)

Rails docs are amazing, but #merge doesn't get enough love. Maybe I'll issue a pull request to improve it with some examples like this and the ones from the article.

1 comments

that’s one of those little niggles i’ve had about rails that gets solved so neatly eventually. i started with rails 3 (#merge is a rails 4 addition) so i didn’t know about #merge for a while (#or was another nice addition), and was doing a lot of that ugly chaining in the beginning. same with js - with the move to frontend without webpacker and node, i’m eager to try out rails 7 alpha to see what the dev ergonomics are like now.