如何在Rails中将参数传递给委托方法
我想有一个仪表板来显示多个模型的摘要,我使用Presenter实现它而没有自己的数据。 我使用ActiveModel类(没有数据表):
class Dashboard attr_accessor :user_id def initialize(id) self.user_id = id end delegate :username, :password, :to => :user delegate :address, :to => :account delegate :friends, :to => :friendship end
通过委托,我希望能够调用Dashboard.address
并返回Account.find_by_user_id(Dashboard.user_id).address
。
如果Dashboard是一个ActiveRecord类,那么我可以声明Dashboard#belongs_to :account
和delegate将自动工作(即,Account会知道它应该返回来自帐户的地址属性, user_id
等于Dashboard实例中的to user_id
)。
但Dashboard不是ActiveRecord类,所以我不能声明belongs_to
。 我需要另一种方法来告诉Account查找正确的记录。
有没有办法克服这个问题? (我知道我可以伪造Dashboard以获得一个空表,或者我可以将User的实例方法重写为带有参数的类方法。但这些解决方案都是hacks)。
谢谢。
当您编写delegate :address, :to => :account
,这会在Dashboard上创建一个新的address
方法,它基本上在同一个对象上调用account
方法,然后在此account
方法的结果上调用address
。 这(非常粗略地)类似于写作:
class Dashboard ... def address self.account.address end ... end
使用当前的类,您所要做的就是创建一个account
方法,该方法返回具有正确user_id
的帐户:
class Dashboard attr_accessor :user_id def initialize(id) self.user_id = id end delegate :username, :password, :to => :user delegate :address, :to => :account delegate :friends, :to => :friendship def account @account ||= Account.find_by_user_id(self.user_id) end end
这将允许您访问这样的地址:
dashboard = Dashboard.new(1) # the following returns Account.find_by_user_id(1).address address = dashboard.address