簡體   English   中英

繼承Ruby on Rails中的活動記錄模型

[英]Inheriting off an active record model in Ruby on Rails

我希望可以繼承一個activerecord模型,並像使用父類一樣使用子類。 事實並非如此,AR關系似乎不適用於該子類。

class Manager < User
  belongs_to :shop
end

class Shop < ActiveRecord::Base
  has_many :managers
end

class PremiumShop < Shop
end

@premium_shop = manager.shop # Finds the shop.
@premium_shop = manager.premium_shop # Does not find the shop, NilClass:Class error

有可能使這項工作嗎?

shop方法對於Manager類的某些實例存在,因為您是通過belongs_to定義的關聯。 您在Manager模型上沒有定義premium_shop方法,因此發生了NilClass錯誤。

如果要為PremiumShop類定義這樣的關聯,則必須顯式指定它。

belongs_to :premium_shop, class_name: "PremiumShop", foreign_key: :shop_id

根據您的需求,您可能還會考慮研究“ rails單表繼承”。

暫無
暫無

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

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