简体   繁体   中英

Ruby on Rails - link_to with parentheses

Sorry, but this is a newbie question.

There are also a lot of questions on "link_to" already, but none answer my question, which I don't think is really specific to link_to ...

Creating a link like this works :

<%= link_to person.automobile_id, person %>

But, trying it like this does not work :

<%= link_to (translation.request_id, translation) %>

This produces an error:

syntax error, unexpected ',', expecting ')'

This confuses me, since to me it looks like I'm just wrapping parenthesis around the arguments for link_to .

What am I misunderstanding?

You have an additional space:

link_to (translation.request_id, translation)

should read:

link_to(translation.request_id, translation)

This is a syntax error in ruby:

[~]$ ruby -e 'def adds(x, y) x+y end; puts adds (1, 2)'
-e:1: syntax error, unexpected ',', expecting ')'
def c(x, y) x+y end; puts adds (1, 2)
                                  ^

In most cases the parentheses to a method argument is optional in Ruby.

link_to("link name", path) 

is equivalent to

link_to "link name", path

The latter example is more idiomatic in the Rails community.

However, the spacing must be preserved. if you omit the parenthesis then there can only be one space between the method and argument. It may look a little strange to someone new to Ruby and Rails, but is used so prevalently you will get used to it quick.

The exception is if you are chaining methods together and one of the earlier methods has an argument then you will need to include the parentheses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM