开发者

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

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!


You should setup has_many :through association not only on orders model, but on users too. As you already have has_many :orders association for user, you can give your association another name, for example, viewable_orders:

class User < ActiveRecord::Base
  has_many :orders
  has_many :viewables
  has_many :viewable_orders, :through => :viewables, :source => :order
end

class Viewable < ActiveRecord::Base
  belongs_to :user
  belongs_to :order
end

class Order < ActiveRecord::Base
  belongs_to :user
  has_many :viewables
  has_many :users, :through => :viewables
end

And then use can use user.viewable_orders to get all orders specific user can view

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜