Questions about relationships in Rails "field must exists"

Asked

Viewed 305 times

0

Good morning,

I started studying Rails recently and whenever I will define the relationships between the entities in my database arise some doubts.

The first time, I created and defined relationships in Migrations. I did so:

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 fields cod_filme and id_locadora and for this I create two foreign keys referencing the two tables. When I made the command rake db:migrate I received no error, but I found a tutorial in which it is done otherwise.

In this tutorial, they modify the template file and define the relationships there. Disas form:

class Preco < ApplicationRecord
    belongs_to :locadora
    belongs_to :filme
end

And after they do that, 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 perform migrate and right. I’m having problems when trying to add a price. I have already created records in video and video rental, but when I try to add a movie I get the error:

["Hire companies must exist"]

I realized that when the relationship is belongs_to the name of the referenced table has to be singular, but even after having modified I keep getting the error.

My question is: do I need to define relationships in Migration files or can I leave to define only in 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 it would help a lot! I think I’m mixing it all up :(

1 answer

1


Hello

You can do the following in Migrations: Rails g scaffold price value:decimal References:rental

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

Answering your question well, you can do only in the models but in the way I explain above you will do everything well, hug.

Hug I hope it helps you.

  • I get it, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.