【问题标题】:rails - Inheritanting class belongs to another modelrails - 继承类属于另一个模型
【发布时间】:2016-04-04 06:01:38
【问题描述】:

我正在制作一个应用程序,其中将有两种不同的产品——默认产品和用户定义产品。我试图仅将 UserProducts 与用户关联,而 DefaultProduct 不需要此字段。我在网上查了一段时间,但没有找到任何结论。

这是我目前尝试过的尝试:

class Product < ActiveRecord::Base
  validates :name, precence: true, length: { maximum: 100 }

  has_many :categories
end

class DefaultProduct < Product
  def self.model_name
    Product.model_name
  end
end

class UserProduct < Product
  def self.model_name
    Product.model_name
  end

  belongs_to :user # Causes the console to spew errors
end

我怀疑使用 STI 是造成问题的主要原因,但我对 Rails 较新,不知道有什么替代方案。

在 Rails 中将另一个模型与继承模型关联的一般方法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 activerecord rails-activerecord


    【解决方案1】:

    所有子模型都保留在父表上,因此您必须在products 表中生成user_id 字段并添加type:string 字段,以用于rails。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-27
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      相关资源
      最近更新 更多