0

I am trying to create a ActiveRecord database by using Ruby on Rails

I have created a database Schema:

enter image description here

To create tables destinations, productions, rules I am using rails generate model Name parameter:integer

How to create a table rule_input with foreign key to rule?

Also, how to create a table or a model sources that would join all these tables and I could get source like: source = Source.find(1) and for example render json: {source: source}?

Daumantas Versockas
  • 797
  • 1
  • 10
  • 29

2 Answers2

1

How to create a table rule_input with foreign key to rule?

Assuming you are asking for cli command - "rails generate model rule_input rule:references"

Also, how to create a table or a model sources that would join all these tables and I could get source like: source = Source.find(1) and for example render json: {source: source}?

Single table inheritance may be a possible solution here.

class Source < ActiveRecord::Base; end

class Rule < Source
  has_many :rule_inputs 
end

class Production < Source; end
class Destination < Source; end

class RuleInput < ActiveRecord::Base
  belongs_to :rule
end

Basically single table inheritance lets different models inherit from a parent model within a single table, as long as your data structure between models are fairly similar this would be a viable option for you. (STI eliminate having 3 tables with all the same columns)

maxhungry
  • 1,863
  • 3
  • 20
  • 28
0

As @maxhungry mentioned you can do STI (Single Table Inheritance) to eliminate using three tables Rules, Productions and Destinations and replace it with "type" column using Source model.

Here are some good articles on STI and about refactoring such models.

https://about.futurelearn.com/blog/refactoring-rails-sti/

http://samurails.com/tutorial/single-table-inheritance-with-rails-4-part-1/

And about your question - do I need to think about model as an object or as a table? Model is not same as Table as we can have table-less models. You may read this Rails model without a table. So if you subclass your model from ActiveRecord::Base then it will point to a Table. For example, this code

class Product < ActiveRecord::Base
end

This will create a Product model, mapped to a products table at the database. But if you just say

class Product
end

then its a table-less model.

Community
  • 1
  • 1
Rohan Daxini
  • 496
  • 4
  • 12