问题描述
我想要一个仪表板来显示多个模型的摘要,我使用没有自己数据的 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 知道它应该从具有 user_id 的帐户返回地址属性
等于 Dashboard 实例中的 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 的实例方法重写为带参数的类方法.但这些解决方案都是 hack).
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
方法,然后调用 address
这个 account
方法的结果.这(非常粗略地)类似于写作:
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 中的委托方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2