DEV Community

Eisea904
Eisea904

Posted on

Common Mistakes when Beginning Rails

Several steps can go wrong when setting up a new rails api. This article will hopefully help debug issues that may arise.

Often when learning any new coding material, example variables like 'project name' are written with with brackets on either side. This is a reminder not to include those brackets. File and repository names can also be easier to reference without typos if they do not contain spaces. The example code below to create a new rails project would be written in the following way:
$ rails new <project name> --api --database=postgresql
$ rails new project_name_api --api --database=postgresql
By including 'api' in the project name we know that this repo only contains our back end and is separate from the frontend.

Next we will talk about creating our migrations and models. There are several pieces of information that go into creating a new model, the Name, attributes, associations, and more; these three will be discussed here with examples. Our example will be a Teacher model that has_many assignments and a joiner model Assignment that belongs to both a Teacher and Student.
'g' is short for 'generate', either can be used here; I will be using 'g'.
Teacher --< Assignment >-- Student

$ rails g model Teacher name:string

  • the model name 'Teacher' is always capitalized
  • if attribute type (name is a string) is not given, then the attribute type will default to a string. Thus the above code could be written as: $ rails g model Teacher name
  • A Teacher has_many Assignments, however this is not the place to include has_many. Do NOT include something like 'assignments:has_many' in this console command. has_many associations only go in the 'app/models' folder.

$ rails g model Assignment name:string teacher_id:integer student_id:integer
OR
$ rails g model Assignment name:string teacher:belongs_to student:belongs_to

  • For our Assignment model either of these will work. The associations can be written either as teacher_id:integer or with the teacher:belongs_to macro which will generate a foreign_key as an integer. The functionality is the same, but the result will look different in the migration folder. If both are included in the console command, the error ArgumentError: you can't define an already defined column 'user_id' will appear when you run db:create and you will not be able to make a 'db/schema' folder or seed any data.

After this, you will put the associations belongs_to :teacher and belongs_to :student in the 'app/models' Assignment file.

Top comments (0)