2010-01-19 37 views
16

documentation(和google)中可以明顯看出如何生成一段鏈接,例如podcast/5#comments。您只需將:anchor的值傳遞給link_to即可。在軌道中定義錨標籤的正確方法是什麼?

我擔心的是生成<a name="comments">Comments</a>標籤,即第一個鏈接的目的地,這個任務非常簡單。

我試過以下,雖然他們似乎工作,標記是不出我所料:

link_to "Comments", :name => "comments" 
link_to "Comments", :anchor => "comments" 

我想我失去了一些東西明顯。謝謝。

+0

對不起,我不認識你* *清楚寫的東西!我的錯!很高興你得到了你需要的答案。我刪除了我的,所以不要混淆任何人:) – 2010-01-19 15:52:19

回答

52

你正在用Ruby的語法糖混淆(這Rails的大汗使用)。在回答你的問題之前,讓我簡單解釋一下。

當紅寶石函數有一個參數,它是一個哈希:

def foo(options) 
    #options is a hash with parameters inside 
end 

你可以「忘記」把括號/括號,並調用它像這樣:

foo :param => value, :param2 => value 

紅寶石將填補空白,並明白,你試圖完成的是這樣的:

foo({:param => value, :param2 => value}) 

現在,對你的問題:link_to需要兩個可選哈希 - 一個被稱爲options和另一個html_options。你可以把它想象這樣的定義(這是一個近似值,它要複雜得多)

def link_to(name, options, html_options) 
... 
end 

現在,如果你調用這樣說:

link_to 'Comments', :name => 'Comments' 

紅寶石將得到一個有點困惑。它會嘗試「填寫空白」爲你,但不正確:

link_to('Comments', {:name => 'Comments'}, {}) # incorrect 

它會認爲name => 'Comments'部分屬於選項,而不是html_options

你必須自己填補空白來幫助紅寶石。把所有的括號的地方,它會像預期的那樣:

link_to('Comments', {}, {:name => 'Comments'}) # correct 

,如果你想,你可以實際刪除最後一組括號:

link_to("Comments", {}, :name => "comments") # also correct 

爲了使用html_options,你必須離開但是第一組括號。例如,您將需要與確認消息和名稱的鏈接做到這一點:

link_to("Comments", {:confirm => 'Sure?'}, :name => "comments") 

其他軌道助手具有類似的結構(即form_forcollection_select),所以你應該學習這種技術。如有疑問,只需添加所有括號。

+0

這正是我一直在尋找的。謝謝! – 2010-01-20 18:55:19

+9

+1不只是給出解決方案,而是爲了解釋它! – Guillaume 2011-12-12 19:27:59

14

如果你想通過rails,我建議content_tagdocs)。

例子:

content_tag(:a, 'Comments', :name => 'comments') 
+1

謝謝,我想這就是我一直在尋找。現在我發現,在haml中,只需要使用'%a {:name =>「comments」}評論來創建該鏈接。我想我只是希望不要在rails中編碼鏈接。 – 2010-01-19 15:41:33

+0

有時只是扔一個標籤更好,但如果你是erb'ing,並不想突破紅寶石,這也是很好:) – theIV 2010-01-20 16:06:48

+0

我仍然喜歡這個答案,但egarcia的是我正在尋找對於。 – 2010-01-20 18:56:16

0
<%= link_to('new button', action: 'login' , class: "text-center") %> 

創造了一個錨標記爲login.html的i.g

<a href="login.html" class = "text-center"> new button </a> 

<a href="admin/login.html" class = "text-center"> new button </a> 

使用

<%= link_to('new button', controller: 'admin', 
    action: 'login' , class: "text-center") %> 
相關問題