[ACCEPTED]-What's the right way to define an anchor tag in rails?-segment
You are getting confused by Ruby's syntactic 27 sugar (which Rails uses profusely). Let 26 me explain this briefly before answering 25 your question.
When a ruby function takes 24 a single parameter that is a hash:
def foo(options)
#options is a hash with parameters inside
end
You can 23 'forget' to put the parenthesis/brackets, and 22 call it like this:
foo :param => value, :param2 => value
Ruby will fill out the 21 blanks and understand that what you are 20 trying to accomplish is this:
foo({:param => value, :param2 => value})
Now, to your 19 question: link_to
takes two optional hashes - one 18 is called options
and the other html_options
. You can imagine 17 it defined like this (this is an approximation, it 16 is much more complex)
def link_to(name, options, html_options)
...
end
Now, if you invoke 15 it this way:
link_to 'Comments', :name => 'Comments'
Ruby will get a little confused. It 14 will try to "fill out the blanks" for you, but 13 incorrectly:
link_to('Comments', {:name => 'Comments'}, {}) # incorrect
It will think that name => 'Comments'
part belongs 12 to options, not to html_options
!
You have to help ruby 11 by filling up the blanks yourself. Put all 10 the parenthesis in place and it will behave 9 as expected:
link_to('Comments', {}, {:name => 'Comments'}) # correct
You can actually remove the 8 last set of brackets if you want:
link_to("Comments", {}, :name => "comments") # also correct
In order 7 to use html_options, you must leave the 6 first set of brackets, though. For example, you 5 will need to do this for a link with confirmation 4 message and name:
link_to("Comments", {:confirm => 'Sure?'}, :name => "comments")
Other rails helpers have 3 a similar construction (i.e. form_for
, collection_select
) so you 2 should learn this technique. In doubt, just 1 add all the parenthesis.
If you want to go through rails, I suggest 1 content_tag
(docs).
Example:
content_tag(:a, 'Comments', :name => 'comments')
<%= link_to('new button', action: 'login' , class: "text-center") %>
created an anchor tag for login.html i.g
<a href="login.html" class = "text-center"> new button </a>
and 1 for
<a href="admin/login.html" class = "text-center"> new button </a>
use
<%= link_to('new button', controller: 'admin',
action: 'login' , class: "text-center") %>
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.