2012-04-27 68 views
1

即時通訊使用rails 3.2.3,並在我的應用程序中獲取奇怪的值。Ruby on Rails - N與N的關係,奇怪的值

我有2個模型,一個用戶和角色,這是一個has_and_belongs_to_many關係。中間表使用role_id和user_id列以及正確的名稱(roles_users)創建。

事情是,當我分配一個用戶角色(創建時通過複選框),然後查看與他們關聯的角色的所有用戶我得到無效的角色ID(如75216410時,它應該只是1或2 ),角色名稱只是「角色」而不是管理員。

我想使用Devise和CanCan,我設置了Devise,但這件事讓我無法繼續。

我的角色和用戶控制器具有傳統的restfull動作,與我們搭腳手架時完全相同。由於DB值是正確的,我相信這不是問題。

我的車型有:

user.rb

class User < ActiveRecord::Base 
    # Devise modules 
    # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable, :registerable 
    devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable 

    #relationships 
    has_and_belongs_to_many :roles 

    #nested attr 
    accepts_nested_attributes_for :roles 

    # Accessible (or protected) attr 
    attr_accessible :username, :email, :password, :password_confirmation, :remember_me, :role_ids 

    # attr_accessible :title, :body 


    #validations 
    validates :username, :presence => true 
    validates :username, :email, :uniqueness => true 

end 

role.rb

class Role < ActiveRecord::Base 
    has_and_belongs_to_many :users 
    attr_accessible :name, :user_attributes, :role_id 

end 

我的用戶和角色的觀點是,你會被腳手架獲得以及相同。 我的用戶指標:

<% @users.each do |user| %> 
    <tr> 
     <td><%= user.username %></td> 
     <td><%= user.email %></td> 
     <td><%= user.roles.id %></td> #should display "1" 
     <td><%= user.roles.name %></td> #should display "admin" 
     <td><%= link_to 'Show', user %></td> 
     <td><%= link_to 'Edit', edit_user_path(user) %></td> 
     <td><%= link_to 'Destroy', user, :confirm => 'Are you sure?', :method => :delete %></td> 
    </tr> 
    <% end %> 

的事情是,這個顯示器,而不是角色ID(1),如69067380.一些隨機數。如果我刷新,這個數字變成另一個隨機數。至於角色名稱,它總是說「角色」而不是「管理員」。 這讓我想起了一個指針內存地址,但我懷疑是這種情況。

注意:當我使用MySQL工作臺檢查表時,一切都很好,表中的所有值都是正確的。

任何幫助表示讚賞,謝謝提前

回答

2

你的用戶有很多角色,所以當u觸發user.roles它會給出一個陣列,而不是單個記錄的嘗試user.roles.firstuser.roles.first.try(:name)它顯示第一role.you可以循環的作用並根據您的要求顯示它們。

+0

好像我對畢竟關係感到困惑。 也許一對多會更好,但無論如何,謝謝你的解釋。 – Silver 2012-04-27 10:34:57

1

user.roles.id是關係本身的標識。您應該選擇其中一個角色,使用user.roles.fist.id或其他。一個用戶可以有很多角色,你可以打算全部打印這些角色。

+0

感謝您的解釋。 – Silver 2012-04-27 10:34:38