How to pass argument to delegate method in Rails

倾然丶 夕夏残阳落幕 提交于 2019-11-29 06:00:58

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!