代表不为我工作?

时间:2013-08-05 06:43:09

标签: ruby-on-rails-3 activerecord

我见过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 个答案:

答案 0 :(得分: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()

的文档