[英]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.