User has_many products
Product belongs_to user
User also has an active_account and created_at column in its table.
I am trying to translate this into a query:
'What products exist where the user that the product belongs to has an active account OR is less than 25 days old?'
This is what I have so far (not sure how to add in the OR less than 25 days old):
Product.joins(:user).where(users: {active_account: true})
A better way is to use Arel
users = Arel::Table.new(:users)
products = Arel::Table.new(:products)
users
.join(products,Arel::Nodes::InnerJoin)
.on(users[:id].eq(products[:user_id]))
.where(users[:active_account].eq(true).or(users[:created_at].lt(25.days.ago))
I would start with something like this:
Product.joins(:user).where(
"users.active_account = :account_active OR users.created_at >= :max_age",
{ :account_active => true, :max_age => 25.days.ago }
)
In a next step I would move that logic into scopes and merge that scopes:
# in user.rb
scope :active, ->{
where("users.active_account = :account_active OR users.created_at >= :max_age", { :account_active => true, :max_age => 25.days.ago })
}
# in product.rb
scope :with_active_user, ->{ joins(:user).merge(User.active) }
What allows you to use it like this:
Product.with_active_user
Try this:
Product.joins(:user).where("users.active_account = ? OR users.created_at >= '#{(Time.now - 25.days).utc.iso8601}'", true)