2012-04-24 96 views
1

我正在使用具有用户和授权模型的Rails应用程序。 Eacch用户可以拥有许多授权,并且每个授权都属于特定用户。我为此使用了belongs_to关联。现在,当我试图使用如何在rails中的belongs_to关联中访问字段

user = User.find(params(:id)) 
auth = user.authorizations 

现在的问题是,当我尝试使用

auth.id 

我没有得到任何方法发现错误访问授权领域访问特定用户的授权,但以下

Authorization.first.id 

工作正常。他们之间有什么区别?

回答

1
auth = user.authorizations 

现在AUTH将授权对象的数组

auth.first.id 

会工作,除非数组不为空

+0

@sounder感谢我错过了一些基础知识在这里 – santosh 2012-04-24 10:22:29

2

如果用户的授权(用户has_many :authorizations然后user.authorizations返回数组实际上它返回AR:Relation,但现在没关系)。所以,如果你想获得第一授权id可以使用user.authorizations.first,如果你想获得该用户的授权,所有的ID,你可以使用user.authorizations.map(&:id)

+0

感谢我错过了一些基础知识在这里 – santosh 2012-04-24 10:22:45

1
@authorizations = user.authorizations 

将返回权限的列表。所以你只要形成一个循环,然后获取字段值。例如

@authorizations.each do |auth| 
    auth.id 
end 
+0

感谢我错过了一些基础知识在这里 – santosh 2012-04-24 10:23:02

相关问题