Search code examples
ruby-on-railsruby-on-rails-4associationsmodels

Rails: access associations within a model


To access a model's attributes within the model, you can call self[:attribute_name], e.g. if you have a :question attribute then you can call self[:question] within the model to access the value for that attribute.

How can I do so for associations? When I try to access associations the same way it comes up as nil. So even though I can access f.subs outside the model, within the model self[:subs] comes up nil.

Thanks!


Solution

  • Can you try self.subs inside the model. if your method is instance method you can always called attributes and association using 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

    assosiated_obj = self.subs.first
    p assosiated_obj.name