Obromios
Obromios

Reputation: 16403

Passing through an association attributes in ruby on rails

I have a model user that has one traversal. The Traversal model has an attribute, frame. I can access it using

user.traversal.frame

but I seem to recall there is a ruby on rails means for making the following work.

user.traversal_frame

without an extra method in the User model i.e. without doing

def traversal_frame
  self.traversal.frame
end

Is there another way to do this?

Upvotes: 0

Views: 57

Answers (1)

Salil
Salil

Reputation: 47542

Use delegate method. Something like following

class User < ActiveRecord::Base
  has_one :traversal
  delegate :frame, to: :traversal
end

You can then use it like following

user.frame # => Same as user.traversal.frame

Note:- when user has no traversal then user.frame will throw an error raises NoMethodError: undefined method 'frame' to fixed this use following

delegate :frame, to: :traversal, allow_nil: true

To access it using user.traversal_frame you have to use prefix option as below

delegate :frame, to: :traversal, prefix: true, allow_nil: true

Upvotes: 3

Related Questions