2013-08-21 121 views

回答

1

這裏是official explanation

委託(*方法)公共

提供一個委託類的方法來輕鬆地將包含的對象的公共方法作爲你自己的。

class Greeter < ActiveRecord::Base 
    def hello 
    'hello' 
    end 

    def goodbye 
    'goodbye' 
    end 
end 

class Foo < ActiveRecord::Base 
    belongs_to :greeter 
    delegate :hello, to: :greeter 
end 

Foo.new.hello # => "hello" 
Foo.new.goodbye # => NoMethodError: undefined method `goodbye' for #<Foo:0x1af30c> 

這裏是它如何與實例工作的一些其他的解釋:

http://brettu.com/rails-daily-ruby-tip-20-use-the-delegate-method-in-rails-to-reduce-code/

http://www.simonecarletti.com/blog/2009/12/inside-ruby-on-rails-delegate/

http://pivotallabs.com/rails-delegates-are-even-more-useful-than-i-knew/