2012-01-16 42 views
13

我有3個表 - 用戶,事物,並遵循。用戶可以通過下表進行關注,將user_idthings_id關聯。這將意味着:需要來自rails連接表的數據,has_many:通過

class User 
    has_many :things, :through => :follows 
end 

class Thing 
    has_many :users, :through => :follows 
end 

class Follow 
    belongs_to :users 
    belongs_to :things 
end 

所以我可以檢索thing.users沒有問題。我的問題是,如果在下面的表中,我有一個名爲「關係」的列,所以我可以設置一個關注者爲「管理員」,我想訪問該關係。因此,在一個循環中我可以這樣做:

<% things.users.each do |user| %> 
    <%= user.relation %> 
<% end %> 

有沒有一種方法,包括關係到原來的用戶對象?我試過:select => "follows.relation",但它似乎沒有加入屬性。

+2

它是一個非常糟糕的主意來命名關係「關係」......這可能會打破一些ruby內部,你會得到意想不到的行爲! – Lichtamberg 2012-01-16 00:44:58

+0

好的,謝謝。可以說這個列被命名爲「is_admin」並且有一個布爾類型.. – 2012-01-16 00:57:07

回答

22

爲此,您需要在has_many中使用一點SQL。像這樣的東西應該有希望工作。 has_many :users, :through => :follows, :select => 'users.*, follows.is_admin as is_follow_admin'

然後在循環中,你應該有機會獲得 user.is_follow_admin

+0

絕對有效,並且基本上是我以前嘗試的。我的掛斷是,在命令行上執行此操作時,SQL轉儲不會在任何地方顯示is_admin屬性。它只顯示以下對象。謝謝! – 2012-01-16 01:20:33

+0

+1 - 布拉德利牧師,你已經做到了。 – 2012-09-08 13:31:56

+0

+1巨大的節省時間和非常優雅,謝謝! – 2012-12-06 19:46:26

0

你也許能夠做一些事情,如:

<% things.follows.each do |follow| %> 
    <%= follow.relation %> 
    <%= follow.user %> 
<% end %> 
8

對於使用軌道4人,的用法:順序:選擇等已被棄用。現在你需要指定如下:

has_many :users, -> { select 'users.*, follows.is_admin as is_follow_admin' }, :through => :follows