2015-06-19 80 views
0

我有三個型號:項目包含階段包含內容Rails的嵌套協會(通過模型模型)

在Projects show.html.erb上,我想顯示與該項目關聯的所有階段,然後顯示與這些階段關聯的內容。

所以這裏就是我在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 %> 

這裏還有什麼是我的projects_controller.rb

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

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

這裏的stage.rb模型:

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

    belongs_to :project 
    has_many :contents 
end 

而這裏的contents.rb

class Content < ActiveRecord::Base 
    belongs_to :stage 
end 

是我得到的錯誤是:

的SQLite3 ::的SQLException:沒有這樣的列:stages.slug:選擇 「階段」 * FROM。 「階段」 WHERE 「階段」, 「廢料」= '脈衝' ORDER BY 「階段」, 「ID」 ASC LIMIT 1

提取的源(圍繞線#16):

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

編輯:問題是它尋找一個階段與項目的id,而不是舞臺的ID。我試圖讓它顯示的舞臺,然後遍歷屬於它的每個內容。

+0

爲什麼你發現通過'PARAMS [ID]你已經去了'/ projects/pulse',然後使用友好的id來找到正確的項目,但是你沒有一個階段的脈衝。你想在第16行做什麼? –

+0

在線16我試圖找到舞臺併發回它的內容 – beaconhill

+0

但是你沒有一個舞臺,你有很多。 –

回答

2

項目控制器:

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

查看:在項目控制器舞臺和項目`:

<% @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 %> 
0

根據friendly_id docs,您必須運行將slug列添加到Stage模型的遷移。確保你已經完成並運行rake db:migrate

這是錯誤的說法:

的SQLite3 ::的SQLException:沒有這樣的列:stages.slug

你還沒有加入該列階段的表格中。

你必須給它一個舞臺的ID。在你的代碼使用的是在這兩個發現同一ID:

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

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

您使用params[:id]兩次。必須有一些其他的參數可以使用,也許假設你設置了嵌套路由。通常情況下,父模型將具有params[:project_id]params[:id]將是嵌套階段模型的標識。

+0

問題是它正在尋找一個帶有項目標識的舞臺,而不是舞臺的標識。 – beaconhill

+0

更新了我的答案。 – DiegoSalazar