beaconhill
beaconhill

Reputation: 451

Rails nested associations (model through a model)

I have three models: Projects which contains Stages which contains Contents.

On the Projects show.html.erb, I want to show all the Stages associated to that Project, then the Contents associated to those Stages.

So here's what I tried in show.html.erb:

<% @stages.each do |stage| %>
  <section name="concept" class="stage">
    <h3><%= stage.name %></h3>

    <% @contents.each do |content| %>
      <p><%= content.name %></p>
    <% end %>

  </section>  
<% end %>

And here's what's in my projects_controller.rb

def show
    project = Project.friendly.find(params[:id])
    @stages = project.stages

    stage = Stage.friendly.find(params[:id])
    @contents = stage.contents
  end

Here's stage.rb model:

class Stage < ActiveRecord::Base
    extend FriendlyId
    friendly_id :name, use: :slugged

    belongs_to :project
    has_many :contents
end

And here's contents.rb:

class Content < ActiveRecord::Base
    belongs_to :stage
end

The error that I'm getting is:

SQLite3::SQLException: no such column: stages.slug: SELECT "stages".* FROM "stages" WHERE "stages"."slug" = 'pulse' ORDER BY "stages"."id" ASC LIMIT 1

Extracted source (around line #16):

stage = Stage.friendly.find(params[:id])

EDIT: The issue is it's looking for a Stage with the id of the project, not the ID of the stage. I'm trying to get the Stage that it's showing and then iterate over each of its Contents that belong to it.

Upvotes: 0

Views: 76

Answers (2)

j-dexx
j-dexx

Reputation: 10416

Projects controller:

def show
  @project = Project.friendly.find(params[:id])
  @stages = @project.stages.includes(:contents)
end

View:

<% @stages.each do |stage| %>
  <section name="concept" class="stage">
    <h3><%= stage.name %></h3>

    <% stage.contents.each do |content| %>
      <p><%= content.name %></p>
    <% end %>

  </section>  
<% end %>

Upvotes: 2

DiegoSalazar
DiegoSalazar

Reputation: 13531

According to the friendly_id docs you have to run a migration that adds the slug column to your Stage model. Make sure you've done this and run rake db:migrate.

This is what the error is saying:

SQLite3::SQLException: no such column: stages.slug

You haven't added that column to the stages table yet.

You have to give it the id of the stage. In your code you're using the same id in both finds:

project = Project.friendly.find(params[:id])
@stages = project.stages

stage = Stage.friendly.find(params[:id])

You're using params[:id] twice. There must be some other params you could use, maybe params[:stage_id] assuming you set up nested routes. Typically though, the parent model would have params[:project_id] and the params[:id] would be the id of the nested stage model.

Upvotes: 0

Related Questions