2013-08-05 2 views
0

Я видел http://rails-bestpractices.com/posts/15-the-law-of-demeter для делегирования, мне это нравится, и я хочу настроить, как показано ниже.Делегат не работает для меня?

Вариант 1:

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 

Я назвал Application.first.user_name => undefined method `user_name' for #<Application:0xb186bf8>

Вопрос 2: Я назвал Application.first.repair_estimated_amount: => undefined method `'repair_estimated_amount' for #<Application:0xb186bf8>

Вопрос 3: Я назвал Application.first.dealership_name: => undefined method `' for #<Application:0xb186bf8>

может любой предложить, как использовать делегат с has_one отношение?

Заранее спасибо Прасад

ответ

1

Вы не использовали опцию префикс, так что вы просто должны вызвать метод без префикса.

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

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

однако, если вы передаете параметр префикс:

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

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

смотрите в документации delegate()

Смежные вопросы