0

私は私resources :tagsの中に持っていroutes.rbます。

そのため/tags/ios、 に移動すると、正しいTag#Showビューが表示されます。

私がしたいのは、ユーザーが/tags/iosそれにアクセスしたときにそれが表示される/iosこと/iosです/tags

eachブロック内でそのリンクをレンダリングする方法の例を次に示します。

<%= link_to "#{tag.name}", url_for(tag) %>
4

3 に答える 3

0

ここでの問題は名前空間です

次のようなルートを定義すると

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アプリのアプリ全体のスラッグルーティングを作成する方法は?

于 2013-03-29T20:08:22.220 に答える
0

あなたの 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}")

http://guides.rubyonrails.org/routing.html

于 2013-03-29T20:11:10.757 に答える
0

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 => /.*/ }
于 2013-03-29T22:51:43.413 に答える