Hello! Slightly trying to learn Ruby on Rails, there is such a task: The task

Actually, the problem is this: I don’t even understand how to create such a model (and what kind of model is it?). It turns out that the first class - Project, in it a link to the second class - Todo? I would like to get help, because Google gives out only either lighter examples, or much more complicated. thank

  • "It turns out that the first class is Project, is there a link to the second class, Todo?" In the direction of the arrows it seems, although common sense and cardinality (what is what and in what quantity), this directly contradicts. It is necessary to check with the compiler. - D-side
  • Okay, how can you make such a model? - Stas Karimov
  • The task said the same generator. Apparently, rails g model Название поле:тип поле2:тип . - D-side

1 answer 1

A project has many tasks - has_many , each task belongs to a belongs_to project .

Model generation

 rails g model Project title:string # project:references - создает отношение таблиц в терминах миграции rails g model Todo text:string isCompleted:boolean project:references 

Or immediately scaffold (to create controllers, models, etc.)

 rails g scaffold Project title:string rails g scaffold Todo text:string isCompleted:boolean project:references 

After creating and before the migration, you can add the necessary parameters to the migration, for example, the default values ​​for the fields.

After complete the migration (update database schema)

 rails db:migrate 

In model classes (app / models / *)

 class Project < ApplicationRecord has_many :todos end class Todo < ApplicationRecord belongs_to :project end 

Can now use

 @project = Project.create({title: 'Project 1'}) @project.todos.create({text: 'todo 1', isCompleted: false}) @todos = @project.todos.all