2016-12-11 40 views
0

我正在創建一個簡單的應用程序,用戶可以在其中填充和保存一些數據到MySQL數據庫。設計:無法解決用戶範圍

每次我將數據保存爲user1,user2都可以看到所有user1,其他用戶可以看到彼此的數據。

模型設置好,has_many和belongs_to,以及外鍵出現在表格上,但我真的很生氣。

希望有人能幫助我

感謝

+0

使用設計的輔助方法'current_user' https://github.com/plataformatec/devise#controller-filters-and-helpers –

+0

嗨佩德羅,我不瞭解這個問題。你希望用戶能夠看到或看不到該數據 – MZaragoza

回答

1

我喜歡做的組段的數據是用戶設置一個賬戶。

一個帳戶擁有衆多用戶,一個用戶屬於一個帳戶

#model 
class Account < ActiveRecord::Base 
    has_many :users 
    ... 
end 

class User < ActiveRecord::Base 
    belongs_to :account 
    ... 
end 

我現在普通用戶devise來驗證我的用戶

現在

application_controller 你可以做這樣的事情

#app/controllers/application_controller.rb 
before_filter :current_account 
def current_account 
    @current_account = current_user.account if current_user 
end 

現在您只需將數據範圍限定爲注意,它屬於

def indedx 
    @users = @current_account.users # this will only return the users associated with that account 
end 

我希望這有助於

+1

認爲你的意思是'@users = current_account.users'在'application_controller.rb'中的 – Swards

+0

**其實''current_user.account'我們正在嘗試做什麼設置了** current_account ** – MZaragoza

+0

由於您創建了'current_account'方法,我懷疑您想要使用它。 – Swards