Durga Prasad
Durga Prasad

Reputation: 935

delegate not working for me?

I have seen http://rails-bestpractices.com/posts/15-the-law-of-demeter for delegation, I like this and I want to customize like below .

Case1 :

    class Application < ActiveRecord::Base
      belongs_to :user
      delegate :name, :to => :user

      has_one :repair, :dependent => :destroy
      delegate :estimated_amount, :to => :repair

      has_one :dealership, :through => :booking
    end

    class User < ActiveRecord::Base
     def name
     return some value
    end
    end

I have called Application.first.user_name => undefined method `user_name' for #<Application:0xb186bf8>

Case2: I have called Application.first.repair_estimated_amount: => undefined method `'repair_estimated_amount' for #<Application:0xb186bf8>

Case3: I have called Application.first.dealership_name: => undefined method `' for #<Application:0xb186bf8>

can any one suggest how to use delegate with has_one relation ?

Thanks in Advance Prasad

Upvotes: 0

Views: 1228

Answers (1)

mkk
mkk

Reputation: 7693

You did not use prefix option, so you should just invoke the method without prefix.

# model.rb
delegate :estimated_amount, :to => :repair

# somewhere else
Application.first.estimated_amount #=> works
Application.first.report_estimated_amount #=> exception!

however, if you pass prefix option:

# model.rb
delegate :estimated_amount, :to => :repair, :prefix => true

# somewhere else
Application.first.estimated_amount #=> exception
Application.first.report_estimated_amount #=> works!

see documentation for delegate()

Upvotes: 2

Related Questions