2011-03-11 38 views
0

如何鏈接以顯示與friendly_id的操作?Rails在使用friendly_url時如何鏈接以顯示動作?

我的看法(不工作):

<% @konkurrencer.each do |vind| %> 
<%= link_to 'vind.name', vind_path %> 
<% end %> 

我的路由文件:

resources :konkurrencer, :controller => 'konkurrancers' 
match '/:id' => 'kategoris#show' 

我希望我的路線是:kategoris /:konkurrancer_name

回答

0

我要做到這一點的英語,因爲我不太瞭解VIND和konkurrencer或它們與等的複數形式的...希望你可以後修改自己:

<% @competitions.each do |competition| -%> 
    <%= link_to competition.name, competition_category_path(competition.category, competition) 
<% end -%> 

路線文件:

# This gives you the route /category/:id 
resource :category do 
    # :controller => 'competitions' is implied 
    resources :competitions 
end 

現在,在你的比賽模式:

class Competition < ActiveRecord::Base 
    belongs_to :category 

    def to_param 
    self.name 
    end 
end 

而在你的分類模型:

class Category < ActiveRecord::Base 
    has_many :competitions 

    def to_param 
    self.name 
    end 
end 

to_param方法告訴rails在您將對象發送給url助手方法時使用該值。所以在我們看來,當我們做了link_to competition.name, competition_category_path(competition.category, competition)時,我們告訴rails使用非id版本來生成url。

確保在你的控制器,你得到的東西出來的數據庫是這樣的:

class CompetitionsController 
    def show 
    @competition = Competition.find_by_name!(params[:id]) 
    @category = Category.find_by_name!(params[:category_id]) 
    end 
end 

讓我知道如果這能幫助:)對不起,我把它改爲英語,我希望我仍然發佈關聯碼。

+0

我不需要創建更新刪除操作。我可以匹配':kategoris /:id'=>'konkurrancers#show'? – 2011-03-11 07:45:36

+0

您可以將:only => [:show]選項添加到任何資源調用。所以你可以把它改成'resources:competitions,:only => [:show]',或者另一個'resource:category,:only => [:show]'我認爲也可以。 – nzifnab 2011-03-11 07:48:41

相關問題