Question

I'm using rails 3.2.3 and have a questions about queries.

I've read that it is favorable using arel instead of named scopes.

Basically in my app, when a user logs in, I want him to see the products that he created. So instead of having in my controllers index:

products=Product.find(:all)

I was looking for something like

products=Product.find(:all, :conditions....)

The thing is, my User and Product models have a HABTM relation (it really has to be) and I don't know how to join those tables so that only the products inserted by the current_user are displayed (the insertion is working correctly)

Do I have to add a search method in my Product model? Or this can be accomplished by passing :conditions in the index controller?

Basically the logic is:

->Get all the products

->inner joining with the products_users HABTM table and get all the products where products_users.user_id = current_user.id. Return the results.

I don't know if I'm missing something here...any tips on how to code this? I'm kind of confused.

Was it helpful?

Solution

if user_sighed_in?
  @products = current_user.products
else
  @products = Product.scoped
end

ofc u have to define association in User model

has_many :products 

OTHER TIPS

If you have associated User and Products models - this code @products = current_user.products will return products of current_user.

To find all the products of current user this will do the trick

   current_user.products 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top