rails override default getter for a relationship (belongs_to)

alias_method is your friend here.

alias_method :original_bar, :bar
def bar
  self.original_bar || Bar.last
end

The way this works is that you alias the default “bar” method as “original bar” and then implement your own version of “bar”. If the call to original_bar returns nil then you return the last Bar instance instead.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)