What is the difference between :to and => in rails [duplicate]
Asked Answered
A

1

5

I have been noticing that the rails community has been moving towards using the ":" notation for more things. And now recently I received a comment in a code review that this:

post 'examples/', to: 'examples#index'

was better than this:

post "examples/" => "examples#index"

My questions are:

  1. Is there a difference between these two statements?
  2. If so why is one better than the other?
  3. Why is the rails community switching to the ":" notation (or are they)?
  4. Moving forward with rails 4 and soon 5, are both formats still acceptable?
Autostrada answered 24/8, 2016 at 17:38 Comment(2)
the colon is a shorthand for when keys are symbols. Will not have any effect from Rails 4 => 5 - this is a ruby language thingEatmon
Technically the first is identical to post "examples/" :to => "examples#index" The post method accepts a number of definitions, including a simple hash.Brandiebrandise
U
14

In context of Rails routes:

  • Is there a difference between these two statements?

There is no difference.

  • If so why is one better than the other?

No, it's the same.

  • Why is the rails community switching to the ":" notation (or are they)?

Just a more readable, 'from' => 'to' and 'from', to: 'to'

  • Moving forward with rails 4 and soon 5, are both formats still acceptable?

Yes.

The => notation it's a hash ruby feature, and related to the :symbol. You can write symbols by two ways :key => value and key: value.

Underdone answered 24/8, 2016 at 17:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.