1.Rails中link_to句法的讲解

link_to与html的<a…a/>元素是对应的。

link_to支持传统的controller/action/id路由风格,同时也支持新的RESTful路由风格。

句法:

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

示例1:

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

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

#RESTful风格的简写
link_to "Profile", @profile
# => <a href="/profiles/1">Profile</a>

示例2:

#传统风格
link_to "Profiles", controller: "profiles"
# => <a href="/profiles">Profiles</a>

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

示例3(method属性):

link_to("Destroy", "http://www.example.com", method: :delete)
# => <a href='http://www.example.com' rel="nofollow" data-method="delete">Destroy</a>

示例4(data属性):

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

原创文章,作者:huoxiaoqiang,如若转载,请注明出处:https://www.huoxiaoqiang.com/ruby/rubyonrails/2021.html

发表评论

电子邮件地址不会被公开。 必填项已用*标注