开发者

Rails how to link to show action when using friendly_url?

How do I link to show action with friendly_id ?

My view (does not work):

<% @konkurrencer.each do |vind| %>
<%= link_to 'vind.name', vind_path %>开发者_Go百科
<% end %>

My route file:

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

I want my route to be :kategoris/:konkurrancer_name


I'm going to do this in english because I don't quite understand the pluralizations of vind and konkurrencer or how they relate etc... Hopefully you can modify it to yourself after:

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

Routes file:

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

Now in your competitions model:

class Competition < ActiveRecord::Base
  belongs_to :category

  def to_param
    self.name
  end
end

And in your category model:

class Category < ActiveRecord::Base
  has_many :competitions

  def to_param
    self.name
  end
end

The to_param method tells rails to use that value any time you send the object to a url helper method. So in our view when we did link_to competition.name, competition_category_path(competition.category, competition) we were telling rails to use the non-id versions to generate the urls.

Make sure in your controller that you are getting the stuff out of the database like this:

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

Let me know if this helps :) Sorry I changed it to english I hope I was still posting relevant code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜