我有類似如下的可能在Rails 3中鏈接查詢?
class Group < ActiveRecord::Base
has_many :group_users
end
class GroupUser < ActiveRecord::Base
belongs_to :user, :group
end
class User < ActiveRecord::Base
has_many :group_users
end
我不使用has_many_through的原因是因爲GROUP_USER類已經不僅僅是一個鏈接表的詳細信息,所以我希望能夠訪問這些值。
我想什麼做雖然是通@groups到頁面中,遍歷組的用戶,但在用戶對象獲取以及
所以
<% @groups.each do |group| %>
<%= group.group_user.user.name %>
<% end %>
爲什麼不能'@ group_users.each'? – 2011-06-29 22:12:33
只是一個簡短的提示,我想你可能會把'has_many:through'與'has_and_belongs_to_many'混淆。 HMT允許連接表中的其他列。 – Brian
好吧,我的第二個代碼示例有點誤導,我實際上在顯示頁面上,所以我確實傳遞了@group對象,因此如果可能,我真的想通過@ group.group_users循環。 – Jhorra