[英]Using a private method with Single Table Inheritance
我正在使用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
我也嘗試將方法放在模塊中,並在每種不同的User類型中都包括該模塊,但是卻遇到相同的錯誤。
我有什么方法可以共享兩種用戶類型的方法並保持私有狀態,而不必將它們明確地放入每個模型中?/是否有更好的策略來解決此問題。
def save_users_access_time
current_user.update_last_seen_at
end
您不能在用戶類自身之外調用私有方法,這就是您遇到問題的原因,您可以將該方法更改為普通的公共方法
無論如何,我實際上認為不需要整個方法,如果要做的只是更新last_seen_at
字段,則可以考慮使用touch
。
def save_users_access_time
current_user.touch(:last_seen_at)
end
在User類中將方法定義為受保護的方法,這將允許派生類使用它。 我認為對方法類型的一個很好的(一般)解釋是: “公共”,“私有”,“受保護”和“無”之間有什么區別? ,希望對您有所幫助。
盡管ruby僅支持以下功能:
Ruby為您提供了三個可訪問性級別:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.