2011-01-26 28 views
1

我有這個方法在我的書的模式,但現在我知道我需要這在一個類別型號還有:我該如何解壓縮以便可以在我的應用的其他部分重用?

def proper_user?(logged_in_user) 
    return false unless logged_in_user.is_a? User 
    user == logged_in_user 
end 

我現在有這個方法的書籍模型和類型模型複製。類別和書籍都有belongs_to:user,並且在表格中也都具有user_id:integer。我只是想把它提取到某個地方,這樣我就可以幹掉它。

我試圖把該方法放在application_controller.rb中,但是它說未定義的方法`proper_user?'爲#

感謝

傑夫

回答

1

我想你會希望能夠調用這個方法是這樣的:

book.proper_user?(current_user)

所以它的工作最好在每個模型來定義它,而在隨後的用戶。

module UserMethods 
    def proper_user?(logged_in_user) 
    # ... etc ... 
    end 
end 

,幷包括它在每一個模型:這是最好的一個模塊與方法混合做

class Book < AR::Base 
    include UserMethods 

class Category < AR::Base 
    include UserMethods 

該模塊可以去在配置/初始化一個源文件,或者你可以將它放在其他地方,並在config/environment.rb中將config.autoload_paths更改爲指向該位置。

+0

我建議把模塊放在lib中。初始化器對於配置代碼來說是一個更好的地方,但對於你自己的庫,lib是最合適的。 – 2011-01-26 10:33:58

0

,因爲這涉及到用戶模式,爲什麼不把它放在那裏?

相關問題