略過內容 略過搜尋

Action View URL Helpers

提供一系列用於建立連結以及取得 URL 的方法,這些 URL 會根據路由子系統而有所不同 (請參閱 ActionDispatch::Routing)。如此一來,您便可以使用相同的連結格式於檢視和控制器中。

命名空間
方法
B
C
L
M
P
S
包含的模組

常數

BUTTON_TAG_METHOD_VERBS = %w{patch put delete}
 

此 helper 可以包含在任何包含路由 URL helper (routes.url_helpers) 的類別中。在此處提供的某些方法僅會在請求內容中運作 (link_to_unless_current,例如),必須提供作為內容中名稱為 request 的方法。

STRINGIFIED_COMMON_METHODS = { get: "get", delete: "delete", patch: "patch", post: "post", put: "put", }.freeze
 

實例公開方法

button_to(name = nil, options = nil, html_options = nil, &block)

產生一個表單,其中包含單一按鈕,此按鈕會提交至由選項組 options 所建立的 URL。這是確保不會因為搜尋機器人或加速器而導致產生您的資料變更的連結的安全方法。

您可以透過 html_options 控制表單和按鈕的行為。html_options 中的大部分值都會傳遞至按鈕元素。例如,在 html_options 中傳遞 :class 選項,將會設定按鈕元素的類別屬性。

可以透過在 html_options 中傳遞 :form_class 選項來設定表單元素的類別屬性。預設為 "button_to",以允許表單及其子項的樣式。

如果物件尚未儲存,表單會預設提交 POST 請求;相反,如果物件已儲存,則會提交 PATCH 請求。如要指定不同的 HTTP 動作,請使用 html_options 中的 :method 選項。

如果從 button_to 產生的 HTML 按鈕不適用於您的版面配置,您可以考慮使用帶有 data-turbo-method 屬性的 link_to 方法,如 link_to 文件中所述。

選項

options hash 會接受與 url_for 相同的選項。如要產生沒有 [action] 屬性的 <form> 元素,請傳遞 false

<%= button_to "New", false %>
# => "<form method="post" class="button_to">
#      <button type="submit">New</button>
#      <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/>
#    </form>"

html_options 中的大部分值都會傳遞至按鈕元素,但有幾個特別的選項

  • :method - HTTP 動詞的符號。支援的動詞有 :post:get:delete:patch 以及 :put。預設為 :post

  • :disabled - 如果設為 true,它會產生一個停用的按鈕。

  • :data - 此選項可用於新增自訂資料屬性。

  • :form - 這個雜湊會是表單屬性

  • :form_class - 這會控制按鈕將被放置於其中的表單的類別

  • :params - 要呈現在表單中作為隱藏欄位的參數的雜湊。

範例

<%= button_to "New", action: "new" %>
# => "<form method="post" action="/controller/new" class="button_to">
#      <button type="submit">New</button>
#      <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6" autocomplete="off"/>
#    </form>"

<%= button_to "New", new_article_path %>
# => "<form method="post" action="/articles/new" class="button_to">
#      <button type="submit">New</button>
#      <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6" autocomplete="off"/>
#    </form>"

<%= button_to "New", new_article_path, params: { time: Time.now  } %>
# => "<form method="post" action="/articles/new" class="button_to">
#      <button type="submit">New</button>
#      <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/>
#      <input type="hidden" name="time" value="2021-04-08 14:06:09 -0500" autocomplete="off">
#    </form>"

<%= button_to [:make_happy, @user] do %>
  Make happy <strong><%= @user.name %></strong>
<% end %>
# => "<form method="post" action="/users/1/make_happy" class="button_to">
#      <button type="submit">
#        Make happy <strong><%= @user.name %></strong>
#      </button>
#      <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"  autocomplete="off"/>
#    </form>"

<%= button_to "New", { action: "new" }, form_class: "new-thing" %>
# => "<form method="post" action="/controller/new" class="new-thing">
#      <button type="submit">New</button>
#      <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"  autocomplete="off"/>
#    </form>"

<%= button_to "Create", { action: "create" }, form: { "data-type" => "json" } %>
# => "<form method="post" action="/images/create" class="button_to" data-type="json">
#      <button type="submit">Create</button>
#      <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"  autocomplete="off"/>
#    </form>"
# File actionview/lib/action_view/helpers/url_helper.rb, line 296
def button_to(name = nil, options = nil, html_options = nil, &block)
  html_options, options = options, name if block_given?
  html_options ||= {}
  html_options = html_options.stringify_keys

  url =
    case options
    when FalseClass then nil
    else url_for(options)
    end

  remote = html_options.delete("remote")
  params = html_options.delete("params")

  authenticity_token = html_options.delete("authenticity_token")

  method     = (html_options.delete("method").presence || method_for_options(options)).to_s
  method_tag = BUTTON_TAG_METHOD_VERBS.include?(method) ? method_tag(method) : "".html_safe

  form_method  = method == "get" ? "get" : "post"
  form_options = html_options.delete("form") || {}
  form_options[:class] ||= html_options.delete("form_class") || "button_to"
  form_options[:method] = form_method
  form_options[:action] = url
  form_options[:'data-remote'] = true if remote

  request_token_tag = if form_method == "post"
    request_method = method.empty? ? "post" : method
    token_tag(authenticity_token, form_options: { action: url, method: request_method })
  else
    ""
  end

  html_options = convert_options_to_data_attributes(options, html_options)
  html_options["type"] = "submit"

  button = if block_given?
    content_tag("button", html_options, &block)
  elsif button_to_generates_button_tag
    content_tag("button", name || url, html_options, &block)
  else
    html_options["value"] = name || url
    tag("input", html_options)
  end

  inner_tags = method_tag.safe_concat(button).safe_concat(request_token_tag)
  if params
    to_form_params(params).each do |param|
      inner_tags.safe_concat tag(:input, type: "hidden", name: param[:name], value: param[:value],
                                 autocomplete: "off")
    end
  end
  html = content_tag("form", inner_tags, form_options)
  prevent_content_exfiltration(html)
end

current_page?(options = nil, check_parameters: false, **options_as_kwargs)

如果目前的要求 URI 是由指定的 options 所產生,則為 True。

範例

假設我們目前處於 http://www.example.com/shop/checkout?order=desc&page=1 動作。

current_page?(action: 'process')
# => false

current_page?(action: 'checkout')
# => true

current_page?(controller: 'library', action: 'checkout')
# => false

current_page?(controller: 'shop', action: 'checkout')
# => true

current_page?(controller: 'shop', action: 'checkout', order: 'asc')
# => false

current_page?(controller: 'shop', action: 'checkout', order: 'desc', page: '1')
# => true

current_page?(controller: 'shop', action: 'checkout', order: 'desc', page: '2')
# => false

current_page?('http://www.example.com/shop/checkout')
# => true

current_page?('http://www.example.com/shop/checkout', check_parameters: true)
# => false

current_page?('/shop/checkout')
# => true

current_page?('http://www.example.com/shop/checkout?order=desc&page=1')
# => true

假設我們目前處於 http://www.example.com/products 動作,並在產品無效時使用 POST 方法。

current_page?(controller: 'product', action: 'index')
# => false

我們也可以傳入符號引數,而不是字串。

# File actionview/lib/action_view/helpers/url_helper.rb, line 548
def current_page?(options = nil, check_parameters: false, **options_as_kwargs)
  unless request
    raise "You cannot use helpers that need to determine the current " \
          "page unless your view context provides a Request object " \
          "in a #request method"
  end

  return false unless request.get? || request.head?

  options ||= options_as_kwargs
  check_parameters ||= options.is_a?(Hash) && options.delete(:check_parameters)
  url_string = URI::RFC2396_PARSER.unescape(url_for(options)).force_encoding(Encoding::BINARY)

  # We ignore any extra parameters in the request_uri if the
  # submitted URL doesn't have any either. This lets the function
  # work with things like ?order=asc
  # the behavior can be disabled with check_parameters: true
  request_uri = url_string.index("?") || check_parameters ? request.fullpath : request.path
  request_uri = URI::RFC2396_PARSER.unescape(request_uri).force_encoding(Encoding::BINARY)

  if %r{^\w+://}.match?(url_string)
    request_uri = +"#{request.protocol}#{request.host_with_port}#{request_uri}"
  end

  remove_trailing_slash!(url_string)
  remove_trailing_slash!(request_uri)

  url_string == request_uri
end

使用由 options 所建立的 URL 來建立具有指定 name 的錨元素。請參閱 url_for 文件中的有效選項。也可以傳入一個字串,而不是一個選項雜湊,這樣會產生一個錨元素,其使用字串的值作為連結的 href。使用 :back 符號,而不是選項雜湊,將會產生一個連結到推薦人(如果沒有推薦人,將會使用 JavaScript 返回連結取代推薦人)。如果 nil 被傳入作為 name,連結本身的值將會變成 name。

link_to(body, url, html_options = {})
  # url is a String; you can use URL helpers like
  # posts_path

link_to(body, url_options = {}, html_options = {})
  # url_options, except :method, is passed to url_for

link_to(options = {}, html_options = {}) do
  # name
end

link_to(url, html_options = {}) do
  # name
end

link_to(active_record_model)
  • :data - 此選項可用於新增自訂資料屬性。

因為它仰賴於 url_forlink_to 支援舊式的控制器/動作/識別碼引數和較新的 RESTful 路線。目前的 Rails 風格只要有可能就偏好 RESTful 路線,所以將你的應用程式建立在資源上,並使用

link_to "Profile", profile_path(@profile)
# => <a href="/profiles/1">Profile</a>

或者更簡潔的

link_to "Profile", @profile
# => <a href="/profiles/1">Profile</a>

取代舊式、冗長、非資源導向的

link_to "Profile", controller: "profiles", action: "show", id: @profile
# => <a href="/profiles/show/1">Profile</a>

類似地,

link_to "Profiles", profiles_path
# => <a href="/profiles">Profiles</a>

比這個更好

link_to "Profiles", controller: "profiles"
# => <a href="/profiles">Profiles</a>

當 name 為 nil 時,會顯示 href

link_to nil, "http://example.com"
# => <a href="http://www.example.com">http://www.example.com</a>

更簡潔一點,當 name 是回傳預設值或模型實例屬性的 Active Record 模型時

link_to @profile
# => <a href="http://www.example.com/profiles/1">Eileen</a>

如果你連結的目標不適合放入 name 參數,你可以使用區塊。 ERB 範例

<%= link_to(@profile) do %>
  <strong><%= @profile.name %></strong> -- <span>Check it out!</span>
<% end %>
# => <a href="/profiles/1">
       <strong>David</strong> -- <span>Check it out!</span>
     </a>

CSS 的類別和 ID 很容易產生

link_to "Articles", articles_path, id: "news", class: "article"
# => <a href="/articles" class="article" id="news">Articles</a>

在使用舊式引數風格時請小心,因為需要額外一個字面雜湊

link_to "Articles", { controller: "articles" }, id: "news", class: "article"
# => <a href="/articles" class="article" id="news">Articles</a>

捨棄雜湊會產生錯誤的連結

link_to "WRONG!", controller: "articles", id: "news", class: "article"
# => <a href="/articles/index/news?class=article">WRONG!</a>

link_to 也可以產生具有錨點或查詢字串的連結

link_to "Comment wall", profile_path(@profile, anchor: "wall")
# => <a href="/profiles/1#wall">Comment wall</a>

link_to "Ruby on Rails search", controller: "searches", query: "ruby on rails"
# => <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>

link_to "Nonsense search", searches_path(foo: "bar", baz: "quux")
# => <a href="/searches?foo=bar&baz=quux">Nonsense search</a>

你可以設定任何連結屬性,例如 targetreltype

link_to "External link", "http://www.rubyonrails.org/", target: "_blank", rel: "nofollow"
# => <a href="http://www.rubyonrails.org/" target="_blank" rel="nofollow">External link</a>

Rails 7 預設啟用 Turbo。Turbo 提供以下 :data 選項

  • turbo_method: HTTP 動詞符號 - 利用指定的 HTTP 動詞執行 Turbo 連結拜訪。執行非 GET 要求時建議使用表單。只有在無法使用表單時,才使用 data-turbo-method

  • turbo_confirm: "question?" - 將確認對話方塊新增到具有指定值的連結。

請查閱 Turbo 手冊,以取得以上選項的更多資訊。

link_to "Delete profile", @profile, data: { turbo_method: :delete }
# => <a href="/profiles/1" data-turbo-method="delete">Delete profile</a>

link_to "Visit Other Site", "https://rubyonrails.org/", data: { turbo_confirm: "Are you sure?" }
# => <a href="https://rubyonrails.org/" data-turbo-confirm="Are you sure?">Visit Other Site</a>

如果condition為真,便使用由一組options建立的 URL 建立一個具有指定name的連結標籤;否則,只會傳回名稱。若要對預設行為進行特別設定,您可以傳遞一個允許使用link_to_if名稱或完整參數清單的區塊。

<%= link_to_if(@current_user.nil?, "Login", { controller: "sessions", action: "new" }) %>
# If the user isn't logged in...
# => <a href="/sessions/new/">Login</a>

<%=
   link_to_if(@current_user.nil?, "Login", { controller: "sessions", action: "new" }) do
     link_to(@current_user.login, { controller: "accounts", action: "show", id: @current_user })
   end
%>
# If the user isn't logged in...
# => <a href="/sessions/new/">Login</a>
# If they are logged in...
# => <a href="/accounts/show/3">my_username</a>

如果condition為假,便使用由一組options建立的 URL 建立一個具有指定name的連結標籤;否則,只會傳回名稱。若要對預設行為進行特別設定(亦即顯示登入連結,而非僅是純文字連結文字),您可以傳遞一個允許使用link_to_unless名稱或完整參數清單的區塊。

<%= link_to_unless(@current_user.nil?, "Reply", { action: "reply" }) %>
# If the user is logged in...
# => <a href="/controller/reply/">Reply</a>

<%=
   link_to_unless(@current_user.nil?, "Reply", { action: "reply" }) do |name|
     link_to(name, { controller: "accounts", action: "signup" })
   end
%>
# If the user is logged in...
# => <a href="/controller/reply/">Reply</a>
# If not...
# => <a href="/accounts/signup">Reply</a>

如果目前的請求 URI 與連結不同,便使用由一組options建立的 URL 建立一個具有指定name的連結標籤;否則,只會傳回名稱(或者,如果已存在區塊,便產生該區塊)。您可以提供一個區塊給link_to_unless_current,對預設行為進行特別設定(例如,顯示「在此開始」連結,而非連結文字)。

假設您有一個導覽選單…

<ul id="navbar">
  <li><%= link_to_unless_current("Home", { action: "index" }) %></li>
  <li><%= link_to_unless_current("About Us", { action: "about" }) %></li>
</ul>

如果在「關於」動作中,它會呈現…

<ul id="navbar">
  <li><a href="/controller/index">Home</a></li>
  <li>About Us</li>
</ul>

…但是如果在「索引」動作中,它會呈現

<ul id="navbar">
  <li>Home</li>
  <li><a href="/controller/about">About Us</a></li>
</ul>

如果目前的動作是指定的動作,則傳遞給link_to_unless_current的內隱區塊會進行評估。因此,如果我們有一個留言頁,並想要呈現一個「返回」連結,而不是連結至留言頁,我們可以執行類似下列的動作…

<%=
    link_to_unless_current("Comment", { controller: "comments", action: "new" }) do
       link_to("Go back", { controller: "posts", action: "index" })
    end
 %>

mail_to(email_address, name = nil, html_options = {}, &block)

建立一個連結標籤,使用 mailto 來鏈結至指定的email_address,除非指定了name,否則該電子郵件地址也會用作連結的名稱。可以在html_options中傳遞連結的其他 HTML 屬性。

mail_to有幾個方法可以通過傳遞特殊鍵值給html_options來自訂電子郵件本身。

選項

  • :subject - 預設電子郵件的主旨。

  • :body - 預設電子郵件的本文。

  • :cc - 在電子郵件中抄送其他收件者。

  • :bcc - 在電子郵件中密件副本其他收件者。

  • :reply_to - 預設電子郵件的回覆給欄位。

混淆處理

於 Rails 4.0 之前, mail_to 提供了編碼位址選項,以阻擋電子郵件收集器。若要利用這些選項,請安裝 actionview-encoded_mail_to gem。

範例

mail_to "me@domain.com"
# => <a href="mailto:me@domain.com">me@domain.com</a>

mail_to "me@domain.com", "My email"
# => <a href="mailto:me@domain.com">My email</a>

mail_to "me@domain.com", cc: "ccaddress@domain.com",
         subject: "This is an example email"
# => <a href="mailto:me@domain.com?cc=ccaddress@domain.com&subject=This%20is%20an%20example%20email">me@domain.com</a>

如果你連結的目標不適合放入 name 參數,你可以使用區塊。 ERB 範例

<%= mail_to "me@domain.com" do %>
  <strong>Email me:</strong> <span>me@domain.com</span>
<% end %>
# => <a href="mailto:me@domain.com">
       <strong>Email me:</strong> <span>me@domain.com</span>
     </a>
# File actionview/lib/action_view/helpers/url_helper.rb, line 487
def mail_to(email_address, name = nil, html_options = {}, &block)
  html_options, name = name, nil if name.is_a?(Hash)
  html_options = (html_options || {}).stringify_keys

  extras = %w{ cc bcc body subject reply_to }.map! { |item|
    option = html_options.delete(item).presence || next
    "#{item.dasherize}=#{ERB::Util.url_encode(option)}"
  }.compact
  extras = extras.empty? ? "" : "?" + extras.join("&")

  encoded_email_address = ERB::Util.url_encode(email_address).gsub("%40", "@")
  html_options["href"] = "mailto:#{encoded_email_address}#{extras}"

  content_tag("a", name || email_address, html_options, &block)
end

phone_to(phone_number, name = nil, html_options = {}, &block)

建立到指定的 phone_number 的 TEL 錨點連結標籤。點選連結時,用於撥打電話的預設應用程式將開啟並輸入電話號碼。

如果未指定 name,則會使用 phone_number 作為連結的名稱。

支援 country_code 選項,其會在連結的電話號碼前加上加號和指定的國家/地區代碼。例如,country_code: "01" 會在連結的電話號碼前加上 +01

連結的其他 HTML 屬性可透過 html_options 傳遞。

選項

  • :country_code - 將國家/地區代碼加到電話號碼之前

範例

phone_to "1234567890"
# => <a href="tel:1234567890">1234567890</a>

phone_to "1234567890", "Phone me"
# => <a href="tel:1234567890">Phone me</a>

phone_to "1234567890", country_code: "01"
# => <a href="tel:+011234567890">1234567890</a>

如果您的連結目標難以放入 name 參數,您也可以使用區塊。ERB 範例

<%= phone_to "1234567890" do %>
  <strong>Phone me:</strong>
<% end %>
# => <a href="tel:1234567890">
       <strong>Phone me:</strong>
     </a>
# File actionview/lib/action_view/helpers/url_helper.rb, line 669
def phone_to(phone_number, name = nil, html_options = {}, &block)
  html_options, name = name, nil if name.is_a?(Hash)
  html_options = (html_options || {}).stringify_keys

  country_code = html_options.delete("country_code").presence
  country_code = country_code.nil? ? "" : "+#{ERB::Util.url_encode(country_code)}"

  encoded_phone_number = ERB::Util.url_encode(phone_number)
  html_options["href"] = "tel:#{country_code}#{encoded_phone_number}"

  content_tag("a", name || phone_number, html_options, &block)
end

sms_to(phone_number, name = nil, html_options = {}, &block)

建立到指定 phone_number 的 SMS 錨點連結標籤。點選連結時,預設的簡訊應用程式會開啟,準備傳送訊息到連結的電話號碼。如果指定 body 選項,則訊息的內容會預設成 body

如果未指定 name,則會使用 phone_number 作為連結的名稱。

支援 country_code 選項,其會在連結的電話號碼前加上加號和指定的國家/地區代碼。例如,country_code: "01" 會在連結的電話號碼前加上 +01

連結的其他 HTML 屬性可透過 html_options 傳遞。

選項

  • :country_code - 在電話號碼前加上國家/地區代碼。

  • :body - 預設訊息主體。

範例

sms_to "5155555785"
# => <a href="sms:5155555785;">5155555785</a>

sms_to "5155555785", country_code: "01"
# => <a href="sms:+015155555785;">5155555785</a>

sms_to "5155555785", "Text me"
# => <a href="sms:5155555785;">Text me</a>

sms_to "5155555785", body: "I have a question about your product."
# => <a href="sms:5155555785;?body=I%20have%20a%20question%20about%20your%20product">5155555785</a>

如果您的連結目標難以放入 name 參數,您也可以使用區塊。ERB 範例

<%= sms_to "5155555785" do %>
  <strong>Text me:</strong>
<% end %>
# => <a href="sms:5155555785;">
       <strong>Text me:</strong>
     </a>
# File actionview/lib/action_view/helpers/url_helper.rb, line 618
def sms_to(phone_number, name = nil, html_options = {}, &block)
  html_options, name = name, nil if name.is_a?(Hash)
  html_options = (html_options || {}).stringify_keys

  country_code = html_options.delete("country_code").presence
  country_code = country_code ? "+#{ERB::Util.url_encode(country_code)}" : ""

  body = html_options.delete("body").presence
  body = body ? "?&body=#{ERB::Util.url_encode(body)}" : ""

  encoded_phone_number = ERB::Util.url_encode(phone_number)
  html_options["href"] = "sms:#{country_code}#{encoded_phone_number};#{body}"

  content_tag("a", name || phone_number, html_options, &block)
end