如何在 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
并且委托会自动工作(即,Account 会知道它应该从具有 user_id
的帐户返回地址属性> 等于仪表板实例中的user_id
)。
但 Dashboard 不是 ActiveRecord 类,因此我无法声明 belongs_to
。我需要另一种方法来告诉帐户查找正确的记录。
有办法解决这个问题吗? (我知道我可以伪造 Dashboard 以拥有一个空表,或者我可以将 User 的实例方法重写为带有参数的类方法。但这些解决方案都是 hack)。
谢谢。
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
By delegate, I want to be able to call Dashboard.address
and get back Account.find_by_user_id(Dashboard.user_id).address
.
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).
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.
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).
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当你写
delegate :address, :to =>; :account
,这会在 Dashboard 上创建一个新的address
方法,该方法基本上调用同一对象上的account
方法,然后调用address
根据此account
方法的结果。 (非常粗略地)类似于编写:使用当前的类,您所要做的就是创建一个
account
方法,该方法返回具有正确的user_id
的帐户:这 将允许您访问这样的地址:
When you write
delegate :address, :to => :account
, this creates a newaddress
method on Dashboard which basically calls theaccount
method on the same object and then callsaddress
on the result of thisaccount
method. This is (very roughly) akin to writing:With your current class, all you have to do is to create an
account
method which returns the account with the correctuser_id
:This would allow you to access the address like this: