Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.


i found that using "super" is the best way

def bar
  super || Bar.last
end

I hope this helps you :D


Randy's answer is spot on, but there's an easier way to write it, using alias_method_chain:


def bar_with_default_find
  self.bar_without_default_find || Bar.last
end
alias_method_chain :bar, :default_find

That creates two methods - bar_with_default_find and bar_without_default_find and aliases bar to the with method. That way you can explicitly call one or the other, or just leave the defaults as is.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!