私は私resources :tags
の中に持っていroutes.rb
ます。
そのため/tags/ios
、 に移動すると、正しいTag#Show
ビューが表示されます。
私がしたいのは、ユーザーが/tags/ios
それにアクセスしたときにそれが表示される/ios
こと/ios
です/tags
。
each
ブロック内でそのリンクをレンダリングする方法の例を次に示します。
<%= link_to "#{tag.name}", url_for(tag) %>
私は私resources :tags
の中に持っていroutes.rb
ます。
そのため/tags/ios
、 に移動すると、正しいTag#Show
ビューが表示されます。
私がしたいのは、ユーザーが/tags/ios
それにアクセスしたときにそれが表示される/ios
こと/ios
です/tags
。
each
ブロック内でそのリンクをレンダリングする方法の例を次に示します。
<%= link_to "#{tag.name}", url_for(tag) %>
ここでの問題は名前空間です
次のようなルートを定義すると
get "/(:slug)" => "Tags#show"
これは基本的に、有効なタグであるかどうかにかかわらず、すべてに一致します。私がそれをする方法は
あなたのルートファイルで:
begin
Tag.all.each do |t|
begin
get "#{t.slug}" => "Tags#show"
rescue
end
end
rescue
end
次に、タグコントローラーで次のことができます
def show
slug = request.env['PATH_INFO']
@tag = Tag.find_by_slug(slug)
end
私の答えは、あなたが興味を持っているかもしれないと私が書いた別の答えから来ていますRailsアプリのアプリ全体のスラッグルーティングを作成する方法は?
あなたの routes.rb で
resources :tags
match '/:tag_name' => 'tags#show'
次に、tags_controller#show アクションで、次の方法でタグ名にアクセスできます。
params[:tag_name]
すべてをキャッチするため、ルートファイルの最後に必ず配置してください。また、有効なタグ名でない場合は 404 をレンダリングする必要があるすべてをキャッチするため:
def show
unless @tag = Tag.where(name: params[:tag_name]).first
raise ActionController::RoutingError.new('Not Found')
end
end
/tags/ruby を /ruby にリダイレクトするには:
match "/tags/:tag_name" => redirect("/%{tag_name}")
So even though I got lots of nice suggestions from these guys, I found what I think is the best solution for me.
All I am trying to do is basically make /tags/ruby
be rendered as /ruby
both in the actual URL on the links of all the tags, and in the URL bar.
I don't want to do anything that will add load to my app.
This is the solution that works for me:
resources :tags, path: "", except: [:index, :new, :create]
Using path:
, you can specify what you want the path to display as. i.e. what do you want to appear before your resource. So if you wanted your URLs to look like myhotness/tags/ruby
, then you would simply do path: "myhotness"
.
I didn't want anything in my path, so I just left it blank.
For what it's worth, you can even add a constraint to that route, like so:
resources :tags, path: "", except: [:index, :new, :create], constraints: { :id => /.*/ }