0

I have a instance variable in my controller that I'm trying to convert into a scope for my model.

Instance variable: products

@products_with_user_differences = Product.where{|p| p.last_user != p.user.username && p.asset_type.name == "Computer" unless p.user.nil? or p.allow_multi_users == true}

Explanation:

This shows all Products that have a last_user value different from the user.username with a type of "Computer". It also excludes any Product that user_id: is nil or have allow_multi_users attribute set to TRUE.

I've tried the following with zero luck: Products.rb

scope :with_user_differences, -> { where(last_user != user.username && asset_type.name == "Computer" unless user.nil? or allow_multi_users == true)}

It doesn't seem to recognize associations or allow "!=" in the scope.

Any ideas or pointers?

Devin
  • 1,011
  • 2
  • 14
  • 30
  • In the first version you're using `where{` and in the second version `where(`. [A normal ActiveRecord `where`](http://guides.rubyonrails.org/active_record_querying.html#conditions) definitely can't do what you're trying to do in your scope. – Mischa Apr 23 '14 at 02:04
  • thanks but i already realize that it can't do that because it doesn't work. any hints on the correct way to do it? – Devin Apr 23 '14 at 02:14
  • Sorry if you think my comment wasn't helpful. I thought it'd help you realise *why* it doesn't work. I put a link in there that may be helpful when trying to rewrite your query. – Mischa Apr 23 '14 at 02:46

1 Answers1

0

The following code will return products that are associated to a user and an asset_type

Product.joins(:user, :asset_type)

To exclude products with allow_multi_users set to true

Product.where(allow_multi_users: false)

To get products where asset_type.name is computer, assuming you followed convention and asset_type is under a table called asset_types

# take note of the pluralized asset_type
Product.where(asset_types: { name: 'Computer' })

To get products where last_user is not equal to the associated user's username

Product.where('products.last_user != users.username')

Given all these, you can do the following

def self.with_user_differences
  Product
    .joins(:user, :asset_type)
    .where(assset_types: { name: 'Computer' })
    .where(allow_multi_users: false)
    .where('products.last_user != users.username')
end
jvnill
  • 29,479
  • 4
  • 83
  • 86