There are 2 classes: Task and Project . Related to each other by has_many - belouse_to .

Class models:

 class Task < ActiveRecord::Base belongs_to :project end class Project < ActiveRecord::Base has_many :tasks, dependent: :destroy end 

How to display project.name value in view task#index ?

Pulling out the project id that owns the current task simple: <%= task.project_id %> , but instead of id can’t display the project name. Tell me how this can be implemented?

  • Hmm ... Did you read the guides at all? .-. - D-side
  • @ D-side read, but I don’t quite understand how unfortunately you can find the answer to the solution of your problem from the written - Alexandr Dmitrenko
  • And where in your controller task filled, since you use it? And why do you use a code in the controller that finds the value and throws it away? - D-side
  • I rolled back the edit with adding a new question after copying / pasting the code from my answer. To this issue, it is not relevant. - D-side
  • Apparently, you have a problem with the awareness of what <%= выражение %> and what the controller should do. I recommend going through the Rails Tutorial . - D-side

1 answer 1

Provided that you were able to get the object of the Task model into the task variable, as indicated by:

Pulling out the project id to which the current task belongs is simple: <%= task.project_id %>

In essence, the project name is returned by the following expression:

 Project.find(task.project_id).name 

... has_many and belongs_to not needed for this. But they are actively used. And not just like that.

You are unlikely to find such a code in real projects , because it is a kind of code, consisting of a large percentage of mechanical juggling of field names in a database, in Rails for this, some conventions have been created and ...


Associations!

The first argument of the association is the name of the method that is created on this model. What does it return? .. depends on the type of model. For belongs_to this is immediately an object of the associated model, so you can do this:

 task.project.name 
  • has_many and belongs_to are needed in the project for other purposes. Added the code you specified - but an undefined local variable or methodtask' for # error occurs - Alexandr Dmitrenko
  • My last answer you should have hinted that my code is for explanation, not for copying. It is built on your supposedly working example: "Pulling out the project id to which the current task belongs is simple: <%= task.project_id %> " - D-side