开发者

class inheritance in ruby on rails - monkeypatching/overriding belongs_to

开发者 https://www.devze.com 2023-02-05 05:45 出处:网络
Simple Rails question. I have a model Foo which looks like this: class Foo < ActiveRecord::Base belongs_to :bar

Simple Rails question. I have a model Foo which looks like this:

class Foo < ActiveRecord::Base

  belongs_to :bar

  def self.belongs_to(association_id, options = {})
    puts "HI"
    super
  end
end
开发者_如何学Go

How come when I load Foo in irb

>> Foo
=> Foo(id: integer, bar_id: integer)
>>

I don't see "HI" (I'm fairly certain Rails calls belongs_to when the class is loaded)? Yet, when I type Foo.belongs_to("anything_here") I see:

>> Foo.belongs_to("anything_here")
HI
=> nil
>>


Not entirely sure what you are trying to accomplish (looks a bit nasty!).

Either way, though, the order of the definition and the call matter:

class Foo < ActiveRecord::Base
  def self.belongs_to(association_id, options = {})
    puts "HI"
    super
  end

  belongs_to :bar
end
0

精彩评论

暂无评论...
验证码 换一张
取 消