Good morning,
I started to study rails recently and whenever I define the relationships between the entities in my database, some doubts arise.
The first time, I created and defined relationships in migrations. I did this:
class CreatePrecos < ActiveRecord::Migration[5.1]
def change
create_table :precos, id: false do |t|
t.decimal :valor, :null => false
t.decimal :valor_anterior
t.string :cod_filme, references: [:Filme, :codigo]
t.string :id_locadora, references: [:Locadora, :id]
t.timestamps
end
add_index :precos, [:cod_filme, :id_locadora], unique: true
end
end
My idea is to create a composite primary key with the cod_filme
and id_locadora
fields and for this I create two foreign keys by referencing the two tables. When I did the command rake db:migrate
I did not receive any errors, but I found a tutorial where it is done in another way.
In this tutorial, they modify the template file and define the relationships there. This way:
class Preco < ApplicationRecord
belongs_to :locadora
belongs_to :filme
end
And after they do this, they add new columns to the tables by creating migrations:
$ rails g migration add_column_id_locadora_to_precos id_locadora
$ rails g migration add_column_cod_filme_to_precos cod_filme
and after that they execute the migrate and that's right. I'm having problems when I try to add a price. I've already created records in a movie store, but when I try to add a movie I get the error:
["Must have"]
I noticed that when the relationship is belongs_to
the referenced table name has to be in the singular, but even after it has been modified I keep getting the error.
My question is: do I need to define the relationships in the migration files or can I leave it to define only in the model files? Should I run a command for the modifications to be applied after I modify the template files? If anyone can pass me a step by step how this should be done would help a lot! I think I'm mixing everything: (