Rails - Logic for finding info from a :has_many :through needed!

Posted by Jty.tan on Stack Overflow See other posts from Stack Overflow or by Jty.tan
Published on 2010-05-22T07:25:23Z Indexed on 2010/05/22 7:30 UTC
Read the original article Hit count: 406

Filed under:
|
|

I have 3 relevant tables. User, Orders, and Viewables

The idea is that each User has got many Orders, but at the same time, each User can View specific other Orders that belong to other Users. So Viewables has the attributes of user_id and order_id.

Orders has a :has_many :Users, :through => :viewables

Is it possible to do a find through an Order's view? So something like

@viewable_orders = Orders.find(:all, :conditions => ["Viewable.user_id=?",1])

To get a list of Orders which are viewable by user_id=1. (This doesn't work, else I won't be asking. :( ) The idea being that I can do something like a sidebar where the current user (the logged-in one) can view a list of other people's orders that he can view. For example

Three other Users who have some Orders that he can view should be eventually displayed like this:

  1. Jack (2)
    • Basic Order (registry_id: 1)
    • New Order (registry_id: 29)
  2. Amy (4)
    • Short Order (registry_id: 12)
  3. Jill (5)
    • Hardware Order (14)
    • Pink Order (17)
    • Software Order (76)

(The number in brackets are the respective user_id or registry_id)

So to find the list of all of the orders that the current user can find (assuming user_id of the current user is 1), would be found by doing

@viewable_orders = Viewable.find(:all, :conditions => ["user_id=?", 1])

And that would give me the collection of the above 6 registries. Now, the easiest way to do this, is for me to just have a list of

+ Jill's Hardware Order
+ Jill's Pink Order
+ Amy's Short Order
+ etc

But that gets ugly for long lists.

Thanks!

© Stack Overflow or respective owner

Related posts about rails

Related posts about has-many-through