2014-10-08 45 views
0

所以我有顧慮玩弄和我讀到一篇有趣的問題凸輪我做了以下內容:我這不是在Rails中使用正確的擔憂4.1.5

class User < ActiveRecord::Base 
    include RoleData 
end 

class User 
    module RoleData 
    extend ActiveSupport::Concern 

    module ClassMethods 

     def role 
     roles.first.try(:role) 
     end 

    end 
    end 
end 

但現在,當我做rails c,做user = User.find(5)和然後做user.role它告訴我這個物體沒有角色方法:NoMethodError: undefined method角色'for#'

那麼,我在做什麼錯了?我在看ryan bates about concerns and services,我很困惑。爲什麼這個用戶類沒有角色方法?

我運行我的測試,他們失敗,不是因爲負載問題,而是因爲缺少或未定義的方法明確定義,就像我甚至不能做current_user.role

我相信這是簡單的。

回答

0

它發生,因爲你定義role方法類的方法,你甚至不需要Concern定義簡單的實例方法,所以你可以寫:

module RoleData 
    def role 
    roles.first.try(:role) 
    end 
end 

,如果你需要的東西,不只是實例方法你可寫:

module RoleData 
    extend ActiveSupport::Concern 

    included do 
    # block will be executed in User class after including RoleDate 
    # you could write here `has_many`, `before_create` etc. 
    # .... 
    end 

    module ClassMethods 
    # class methods 
    # .... 
    end 

    # instance methods 
    # .... 
end