2013-05-03 44 views
2

以下嘗試似乎有效,但不是我試圖歸檔的「乾淨」結果。具有可選參數的路線

以下的路徑,

get "/learn(/:category)", to: "users#index", as: "learn" 

應該是可用的東西像「/學習/技術」 - 如果在地址欄中手工輸入,其中一期工程。

如果我努力實現類似的我的觀點,我得到以下內容:「/ learn?category = technology」 - 哪個好,技術上可行,但不是我想要的。

我用我的觀點裏以下:

- Category.promoted.limit(7).each do |category| 
    %li.category-button 
    = link_to learn_path(category) do 
     = button_tag "", :class => "#{category.name}" 
     = content_tag(:span, category.to_s, :class => 'category-head') 

我的分類模型看起來如下:

class Category < ActiveRecord::Base 
    has_many :skills 

    validates_uniqueness_of :name 

    scope :promoted, lambda { where(:promoted => true) } 

    def to_s 
    read_attribute(:name).titleize 
    end 

    def to_param 
    name.parameterize 
    end 
end 

我將如何實現「清潔」的解決方案?

編輯:

以下工作 - 但必須有比這更好的解決方案呢?

get "/learn", to: "users#index", as: "learn" 
get "/learn/:category", to: "users#index", as: "filter_learn" 
+0

他們的另一條路線叫做學習? – 2013-05-03 07:35:46

+0

不 - 沒有。編輯顯示它是如何工作的,'技術上'。但我認爲musst會是更好的方式嗎? – mlang 2013-05-04 04:16:08

回答

0

試着改變你的鏈接如下:

... 
= link_to learn_path(category: category.name) do 
... 
+0

已經嘗試過 - 問題依然存在。 – mlang 2013-05-03 07:07:44

+0

你也可以試試我更新的帖子嗎? – 2013-05-03 07:09:16

+0

是的 - 遺憾的是仍然沒有解決問題。 – mlang 2013-05-03 07:10:52

0

您可以使用url_for來解決這個問題。

假設我有UsersControllerindex行動,這在routes.rb

resources :users, only: [:index] do 
    collection do 
    get ':kind', :to => 'users#index' 
    end 
end 

然後當我在/用戶頁面,我可以用url_for這樣:

= link_to 'Kind1', url_for(kind: :students) 

將產生路徑:

/users/students 

如果我在另一個頁面上(另一個控制器或另一個操作),那麼我應該提供更多信息。例如,當我另一個控制器的頁面上,然後我應該同時提供controlleraction PARAMS如果目標行爲是不是index(如果目標行爲是index那麼就足以提供僅controller):

= link_to 'Kind1', url_for(controller: :users, action: :index, kind: :students) 

它產生相同的路徑:

/users/students 

在使用users_path(kind: :students)你會得到:

/users?kind=students