tots_o_tater
tots_o_tater

Reputation: 549

rails - Inheritanting class belongs to another model

I'm making an app where there will be two different kinds of products--default and user defined. I'm trying to associate only UserProducts with a user whereas a DefaultProduct will not require this field. I've looked online for a while but haven't found anything conclusive.

Here's the attempt I've tried so far:

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

I suspect using STI is a large contributor to the problem, but am newer to Rails and don't know of alternatives.

What's the general way to associate another model with an inheriting model in rails?

Upvotes: 0

Views: 55

Answers (1)

Mike Belyakov
Mike Belyakov

Reputation: 1375

All child models stay on parent table, so you must generate user_id field in products table and also add type:string field, for rails purposes.

Upvotes: 2

Related Questions