【发布时间】:2015-02-21 01:09:45
【问题描述】:
我正在开发一个 Rails 应用程序,其中有 2 种不同类型的用户(MasterClientUser 和 AccountManager)。我正在使用单表继承来区分用户。我有一个 update_last_seen_at 私有方法,需要在 AccountManager 和 MasterClientUser 上调用。我正在尝试将其放入用户模型中,但出现以下错误:
private method `update_last_seen_at' called for #<MasterClientUser:0x007fc650d2cad0>
从 HomeController 调用 update_last_seen_at 方法:
class HomeController < ApplicationController
before_action :authenticate_user!, :save_users_access_time, only: [:index]
def index
@user = current_user
end
def save_users_access_time
current_user.update_last_seen_at
end
end
型号
class User < ActiveRecord::Base
end
class MasterClientUser < User
private
def update_last_seen_at
self.update_attributes(last_seen_at: Time.now)
end
end
class AccountManager < User
end
我也尝试将方法放入一个模块中,并将该模块包含在每个不同的用户类型中,但我得到了同样的错误。
有什么方法可以共享两种用户类型的方法并保持私有,而不必明确地将它们放入每个模型中?/有没有更好的策略来解决这个问题。
【问题讨论】:
-
调用 update_last_seen_at 的代码在哪里?私有方法不能有明确的接收者。你能在没有明确接收者的情况下编写调用吗?
-
只要把它放在
User中就可以在所有子类中访问。如果您收到此错误,则表示您正在调用此方法破坏对象隐私,因此我们需要查看调用该方法的代码行。 -
已更新以显示调用 update_last_seen_at 方法的位置
-
编辑后-如果要在控制器中调用模型上的方法,它不是私有方法。那你为什么要把它设为私有呢?
标签: ruby-on-rails ruby single-table-inheritance private-methods