如何在Rails中将参数传递给委托方法 [英] How to pass argument to delegate method in Rails
问题描述
我希望有一个仪表板来显示多个模型的摘要,并且我使用Presenter来实现它而没有自己的数据.我使用ActiveModel类(没有数据表):
I would like to have a Dashboard to display summary of multiple models, and I implemented it using Presenter without its own data. I use an ActiveModel class (without data table):
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
.
By delegate, I want to be able to call Dashboard.address
and get back Account.find_by_user_id(Dashboard.user_id).address
.
如果Dashboard是ActiveRecord类,那么我可以声明Dashboard#belongs_to :account
,并且委托将自动运行(即Account知道它应该从Dashboard实例中的user_id
等于to user_id
的帐户返回地址属性).
If Dashboard was an ActiveRecord class, then I could have declared Dashboard#belongs_to :account
and delegate would work automatically (i.e., Account would know it should return address attribute from account with user_id
equals to user_id
in Dashboard instance).
但是Dashboard不是ActiveRecord类,因此我无法声明belongs_to
.我需要另一种方法来告诉Account查找正确的记录.
But Dashboard is not an ActiveRecord class, so I can't declare belongs_to
. I need another way to tell Account to lookup the right record.
有没有办法解决这个问题? (我知道我可以伪造Dashboard来拥有一个空表,或者我可以将User的实例方法重写为带有参数的类方法.但是这些解决方案都是黑客.)
Is there a way to overcome this problem? (I know I can fake Dashboard to have an empty table, or I can rewrite User's instance methods to class methods that take argument. But these solutions are all hacks).
谢谢.
推荐答案
编写delegate :address, :to => :account
时,这将在Dashboard上创建一个新的address
方法,该方法基本上在同一对象上调用account
方法,然后调用<此account
方法的结果上的c7>.这(大致)类似于写作:
When you write delegate :address, :to => :account
, this creates a new address
method on Dashboard which basically calls the account
method on the same object and then calls address
on the result of this account
method. This is (very roughly) akin to writing:
class Dashboard
...
def address
self.account.address
end
...
end
对于当前的类,您要做的就是创建一个account
方法,该方法返回具有正确的user_id
的帐户:
With your current class, all you have to do is to create an account
method which returns the account with the correct 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
这将允许您访问如下地址:
This would allow you to access the address like this:
dashboard = Dashboard.new(1)
# the following returns Account.find_by_user_id(1).address
address = dashboard.address
这篇关于如何在Rails中将参数传递给委托方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!