Rails method arguments: has_many and belongs_to

Shawn Rebello
  If you are used to C/C++/Java , then you would be call a method create_user(), with a parameter "Shawn" using:


create_user("Shawn")

In Ruby parenthesis are optional and this give us cleaner function calls like:

create_user "Shawn"

Consider the methods has_many and belongs_to



belongs_to :author
has_many :pages

A lot of beginners 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:



  belongs_to(:author)
  has_many(:pages)

Alternatively, you could also use a string and pass it as a symbol:



  belongs_to "author".to_sym
  has_many "pages".to_sym

Or..


  belongs_to "author".intern
  has_many "pages".intern


As you can see there is no Rails magic involved, it is just that the creator of Rails decided to go with this syntax.
Also 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 you!

Drop a comment if you have any questions.

Shawn Rebello / Author & Editor

Shawn Rebello is an engineering student who likes learning new languages, tools, libraries or frameworks. When he is not coding, he binge watches TV shows and spends time on Wikipedia and Reddit.

2 comments :

Leave a comment here!