N
N
Nazar Jeveling2014-07-23 23:04:40
Ruby on Rails
Nazar Jeveling, 2014-07-23 23:04:40

How to link two tables in Rails?

Hello! I have a problem, I immediately ask you not to scold me for being a teapot, and so. I have an application in ToDo, and I need to link the Project(id, name) table with the Task(id, name, status, project_id) table. So that in one project there are many tasks.
I need to create a task for the current project. How?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrew Emelianenko, 2014-07-23
@xo8bit

You need a has_many relationship. To do this, in the Project model you need to register:

# project.rb
has_many :tasks

# вызывать так
project = Project.first
project.tasks            # список всех тасков у проекта
project.tasks.create({ ... })  # создание нового таска

You can read more here: rusrails.ru/active-record-associations#svyaz-has_many

B
brikstar, 2014-07-27
@brikstar

And how to display all this in the viewer in the form of a tree?

<% @projects.each do |project| %>
  <%= project.name %><br/>
  <% Project.find(project.id).tasks.each do |task| %>
    <%= task.name %><br/>
  <% end %>
<% end %>

That's right?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question