2014-10-08 46 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