2015-02-10 98 views
0

我是Rails新手,在我的第一個項目上工作 - 這是一個跟蹤我所有漫畫的應用程序。 「系列」has_many「漫畫」和「漫畫」屬於「系列」。Rails 4:在顯示頁面上的範圍has_many/belongs_to關係

我正在使用Rails 4和Ruby 2.1.3。

在我的系列展示頁面上,我列出了屬於該系列的所有漫畫。我希望能夠將它們排序爲發行編號或讀取/未讀狀態。

所以,我已經寫在我的漫畫模型如下:

class Comic < ActiveRecord::Base 
    belongs_to :series 

    validates :number, :title, presence: true, uniqueness: true 

    scope :issue_sort, -> { joins(:series).order(number: :asc)} 
    scope :read, -> { joins(:series).issue_sort.where("read == true") } 
    scope :unread, -> { joins(:series).issue_sort.where("read == false") } 

end 

我的系列模型是這樣的:

class Series < ActiveRecord::Base 
    has_many :comics, dependent: :destroy 

    validates :name, presence: true, uniqueness: {case_sensitive: false } 
end 

此控制檯中的所有的作品,但我的問題當我嘗試在我的Series展示頁面上實現這個功能時,我的確是這樣。

我很確定我需要設置一個自定義路由,它需要一個路由參數。在我的系列控制器

我的表演動作看起來是這樣的:

def show 
    @series = Series.find(params[:id]) 

    case params[:scope] 
    when 'issue_sort' 
    @comics = @series.comics.issue_sort 
    when 'read' 
    @comics = @series.comics.read 
    when 'unread' 
    @comics = @series.comics.unread 
    else 
    @comics = @series.comics.issue_sort 
    end 
end 

但我不能讓我的路線上班。我在我的routes.rb文件中嘗試了以下三個,並且所有三個都給我一個錯誤。

嘗試#1

在我的routes.rb文件:

get '/series/filter/:scope' => "series#show", as: :filtered_comics 

在我的節目模板:

<%= link_to "Issue Number", filtered_comics_path(:issue_sort) %> 

嘗試#2

在我routes.rb f ILE:

get '/series/:series_id/filter/:scope' => "series#show", as: :filtered_comics 

在我的節目模板:

<%= link_to "Issue Number", filtered_comics_path([@series, :issue_sort]) %> 

嘗試3

在我的routes.rb文件:

get '/series/:series_id/comics/:id/filter/:scope' => "series#show", as: :filtered_comics 

在我的節目模板:

<%= link_to "Issue Number", filtered_comics_path([@series,@comics :issue_sort]) %> 

我認爲第二次嘗試可能是要走的路,但我並不完全確定。設置了這種方式,它讓我看到了以下錯誤:

的ActionController :: UrlGenerationError在系列#顯示 顯示/用戶/吉恩/文檔/編碼/ my_projects /漫畫/連環畫/應用/視圖/系列/節目html的。erb哪裏有第6行: 沒有路由匹配{:action =>「show」,:controller =>「series」,:format => nil,:id =>「1」,:scope => nil,:series_id => [#,:issue_sort]}缺少必需的鍵:[:scope]

將這些範圍寫在漫畫模型上會更好嗎?是否有可能從我的系列節目頁查詢漫畫?

任何幫助,將不勝感激。謝謝!

+0

我不確定,但一旦嘗試此操作:'<%= link_to「問題編號」,filtered_comics_path(@series,「issue_sort」)%>' – Deep 2015-02-10 01:32:57

回答

0

我不確定你的路由等,但我相信這會奏效。

<%= link_to "Issue Number", filtered_comics_path(@series, :scope => 'issue_sort') %> 

看着你的路線,你不需要一個@comic變量傳入;你不會使用它。你確實需要你的@series變量。

在你的控制器中,你基於params [:scope]進行切換,所以你必須給出key:scope,以及你想要基於哪個值進行排序。

希望有所幫助。