When I first started using rails, I thought that active record associations like these:
1 | belongs_to :author |
were some sort of a config DSL, that Rails parsed & handled.
I was surprised to find out, that it was not Rails magic.
If you are used to C/C++/Java , then you would be call a method create_user(), with a string
parameter “Shawn” using:
1 | create_user("Shawn") |
In Ruby, parenthesis are optional and this give us cleaner function calls like:
1 | create_user "Shawn" |
Consider the methods has_many and belongs_to
1 |
|
A lot of beginners (including myself) may not realize that the belongs_to :author is just a method call with a symbol as a parameter.
It could have also been written like this:
1 |
|
Alternatively, you could also use a string and pass it as a symbol:
1 |
|
Or..
1 |
|
As you can see there is no Rails magic involved, it is just that the creator of Rails decided to go with this syntax.
The Rails community prefers to use symbols over strings for internal identifiers.
To know the benefits of this approach you can check out this thread.
Hope this helped!