Michael Michael - 1 year ago 38
Ruby Question

When are option hashes (at the end) not allowed in rails 4?

In Ruby on Rails Tutorial 3rd Edition (6.2 user validations)
While writing some test, the book has this code for the ActiveRecord User class:

class User < ActiveRecord::Base
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: case_sensitive: false

The last line ( uniqueness: case_sensitive: false ) throws a syntax error.

The online version for this is corrected to have {} :
https://www.railstutorial.org/book/modeling_users to

uniqueness: { case_sensitive: false }

But my question is why does the last line throw an error? I thought the last hash could always omit the {}?

Answer Source

It throws an error because the following statement is not a valid Ruby statement:

uniqueness: case_sensitive: false

It should be

{ uniqueness: { case_sensitive: false }} 

When passing a Hash to a method, you can omit the {}.

call_method(foo: "bar")
call_method({ foo: "bar" })

But in your case it's completely different: you are defining a hash containing keys such as presence, format, uniqueness. The value of the key uniqueness is supposed to be a Hash as well, but you are not defining it properly.

call_method(foo: { bar: "baz" }) # valid
call_method({ foo: { bar: "baz" }}) # valid
call_method(foo: bar: baz) # invalid