2013-12-08 51 views
1

link_to和helpers使用我的模型和他們的ID的名稱,而我想在我的鏈接中有幾個不同的,任意的變量。我沒有任何問題來路由它們,實際上我也保留了默認路由,但是我突然發現我無法輕鬆生成任意鏈接。例如我想要有一個像「:name_of_board /:post_number」的鏈接,其中:name_of_board和:post_number是由我設置的變量,當我使用link_to時,我得到的是「posts /:id」,其中「posts」是控制器的名稱。雖然它不難使用任意的ID像如何在Rails中創建任意鏈接?

link_to 'Reply', :controller => "posts", :action => "show", :id => number 

我不能得到我如何擺脫「職位」。那麼,有沒有一種簡單的方法來通過變量生成鏈接或將字符串轉換爲鏈接?當然,我可以將其他查詢添加到上面的行中,但它會使鏈接更加難看,如「posts /:id?name_of_board =:name_of_board」。

+0

將有助於看到您的路線 – marvwhere

回答

0

你可以在你的routes.rb創建自己的帖子資源的其他途徑,或使命名路由獨立:

resources :posts do 
    get ':name_of_board/:id' => 'posts#show', as: :with_name_of_board 
end 

get ':name_of_board/:id' => 'posts#show', as: :board 

現在這個

@name_of_board = "foo" 
@post_id = 5 

link_to 'Reply', posts_with_name_of_board_path(@name_of_board, @post_id) 

link_to 'Reply', board_path(@name_of_board, @post_id) 

將分別鏈接到/posts/foo/5/foo/5

+0

謝謝,它的工作。不能添加代表,太低級別:3 – user3079765

0

你應該先編輯您的路由表項,例如經典的表演路線是如下:

get "post/:id" => "post#show", :as => :post 
# + patch, put, delete have the same link but with different method 

而且你可以用下面的助手稱其

link_to "Show the post", post_path(:id => @post.id) 

您可以編輯或創建路線中的新條目,應用您要使用的參數,例如:

get "post/:id/:my_platform" => "post#show", :as => :post_custom 

T母雞

link_to "Show the post with custom", post_custom_path(:id => @post.id, :my_platform => "var") 

最後,對於這最後一項產生的鏈接,例如:

"/post/3/var" 

即使在這種情況下,您可以添加路由沒有定義的其它一些參數,可以如:

link_to "Show post with params", post_custom_path(:id => @post.id, :my_platform => "var", :params1 => "var1", :params2 => "var2") 
=> "/post/3/var?params1=var1&params2=var2" 

當您渲染鏈接時(請記住這些變量是必需的),RoR會與路線中定義的變量相匹配,但您可以添加網址末尾的其他變量("?...&.."

+0

也謝謝你。 :3 – user3079765