简体   繁体   English

Rails:模型内的访问关联

[英]Rails: access associations within a model

To access a model's attributes within the model, you can call self[:attribute_name] , eg if you have a :question attribute then you can call self[:question] within the model to access the value for that attribute. 要访问模型中的模型属性,可以调用self[:attribute_name] ,例如,如果您具有:question属性,则可以在模型中调用self[:question]来访问该属性的值。

How can I do so for associations? 我如何才能建立关联? When I try to access associations the same way it comes up as nil. 当我尝试以相同的方式访问关联时,它显示为nil。 So even though I can access f.subs outside the model, within the model self[:subs] comes up nil. 因此,即使我可以在模型外部访问f.subs ,在模型内部self[:subs]还是f.subs

Thanks! 谢谢!

Can you try self.subs inside the model. 您可以在模型中尝试self.subs if your method is instance method you can always called attributes and association using self.subs 如果您的方法是实例方法,则始终可以使用self.subs调用属性和关联

self.subs will return you all assosiated objects against self (which is your current object. To get any attribute eg name of assosiated model. you can simply try this self.subs将返回所有与self对象(这是您当前的对象。要获取任何属性,例如,关联模型的名称。您可以简单地尝试一下

assosiated_obj = self.subs.first
p assosiated_obj.name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM