簡體   English   中英

對單表繼承使用私有方法

[英]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為您提供了三個可訪問性級別:

  1. 每個人都可以調用公共方法-無需執行訪問控制。 默認情況下,一個類的實例方法(這些不僅僅屬於一個對象;而是,該類的每個實例都可以調用它們); 任何人都可以打電話給他們。 initialize方法始終是私有的。
  2. 受保護的方法只能由定義類及其子類的對象調用。 訪問權限保留在家庭內部。 但是,受保護的使用受到限制。
  3. 顯式接收者無法調用私有方法-接收者始終是自身。 這意味着只能在當前對象的上下文中調用私有方法。 您不能調用另一個對象的私有方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM