Skip to main content

Nested Forms Tutorial: How do you display the Tasks in the Project Index and Show Views?

Rails • Asked by Ryan Kulp

I am trying to display the Tasks on the Products#index and get Type Error in Projects#index
"can't cast Enumerator"

How can I display attributes from tasks on the Products views?

Here's my code -
ProjectsController:

def index
@projects = Project.all
@projects_id = @projects.find(:project_id)
@tasks = Project.where(:project_id => @projects_id).all
end

Projects#index:
<% @tasks.each do |task| %>
<%= task.description %>
<% end %>

AddIndexToTask migration:
def change
add_index :tasks, :project_id
end


I got it working.

def index
@projects = Project.all
end

Projects#index:

<% project.tasks.each do |task| %>
<%= task.description %>
<% end %>


While above solution works, looks like you had a typo here:
@tasks = Project.where(:project_id => @projects_id).all

instead of @tasks = Task.where(:project_id => @projects_id).all


Thanks @eelcoj ! I caught that and it still wouldn't work so I dropped the two lines in the controller. Then used project.tasks.each block in the index so I didn't have to create an instance variable after all.


Ah, another typo—though you got it working, but for maintainability—a (possible) solution. @projects_id returns an object, while it needs an array. That line should be something like this: @projects_id = @projects.find(:project_id).pluck(:id) (which should return [1, 2, 3].


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.