2016-02-01 60 views
0

我有兩個表用戶和組。從關聯中獲取數據

user  group 
----- ------- 
id  id 
name  group_name 
      created_by 

在我的用戶模型我都用過,has_and_belongs_to_many :groups, dependent: :destroy

在我的組模型我都用過,has_and_belongs_to_many :users, dependent: :destroy

我在我的組控制器創建遷移

class UserGameGroup < ActiveRecord::Migration 
    def change 
    create_table :user_game_group, id: false do |t| 
     t.belongs_to :user, index: true 
     t.belongs_to :group, index: true 
    end 
    end 
end 

所以的show方法,我想爲特定組獲取用戶。 假設我目前在第4組,我想根據該組獲取所有用戶。

我可以這樣做Group.where(group_id: 4)但它只會給我用戶的id。有沒有辦法獲得用戶的名字呢?

回答

2

想,如果我目前在第4組,我想根據該組

@group = Group.find 4 
@group.users.each do |user| #-> collection of User objects for @group 
    user.name 
end 
所有使用者去取

您的連接表名是錯誤的。

has_and_belongs_to_many,它應該是[alphabetical_first_plural]_[alphabetical_second_plural],你的情況groups_users

class UserGameGroup < ActiveRecord::Migration 
    def change 
    create_table :groups_users, id: false do |t| 
     t.belongs_to :user, index: true 
     t.belongs_to :group, index: true 
    end 
    end 
end 

如果你想使用你的表名,你就必須在模型中顯式定義join_table選項:

#app/models/user.rb 
class User < ActiveRecord::Base 
    has_and_belongs_to_many :groups, join_table: :user_game_groups 
end 

#app/models/group.rb 
class Group < ActiveRecord::Base 
    has_and_belongs_to_many :users, join_table: :user_game_groups 
end 

要填充連接表,你可以使用<< & .delete methods

@user = User.find x 
@group = Group.find y 

@user.groups << @group 
@user.groups.delete @group 
+0

我user_game_groups表是空的,所以當我用你的代碼我得到空數組,但是我有我的用戶數據以及分組表。爲什麼我會得到空的答覆?所以我檢查了我的數據庫,我不能添加任何東西到user_game_groups表 –

+0

我會添加更新 –

1

在您當前的示例中,您正在查詢一個將使用方法users的組。同樣,您可以使用此調用來檢索用戶記錄的集合。

group = Group.where(group_id: 4) 
group.users # Returns a collection of users. 

如果你想使你可以使用ActiveRecord::QueryMethodsinclude方法,像這樣一個查詢。

Group.includes(:user).where(group_id: 4) 
1

您應該將您的加入組重命名爲groups_users。 Rails期望加入組使用這種格式(連接表第一個字母表和第一個表以_分隔)。加上兩者都應該是複數。此外,您的表名稱組和用戶都應該是複數形式,例如groupsusers,否則您必須在模型上手動指定表名稱。

此外,爲了取名字或者其他屬性的用戶,你可以像

group = Group.find(4)  
group_users = group.users 

group_users的東西會給你所有屬於組ID的用戶列表4