ruby-on-railsruby-on-rails-3arelnamed-scope

Ruby on Rails - How to Query on model/condition on controller?


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.


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