Questions about relationships in Rails "field must exists"

0

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: (

    
asked by anonymous 27.07.2017 / 15:42

1 answer

1

Hello

You can do the following in migrations: rails g scaffold price value: decimal references: locator references: movie

So Rails will create the migration and model price correctly saying that this model relates to rental and movie, will also create in your form, index and view, and refer to the id of related tables. In the Lesson and Movie model then you add a has_many: prices.

Well, if you have a question, you can do it only in the models, but in the way I explained above, you will do everything right, hug.

I hope this helps you.

    
02.08.2017 / 15:32