1

I started with rails two months ago, I still like it but there is one huge problem. It's about the heavy use of hashes in rails forms.

There are so many possible ways how to do that and I've seen alot of examples depending on hashes but it's always an another synstax.

some write it like this

:foo => :bar
foo: :bar
"foo" => "bar"

I always mix them up and get alot of syntax errors , can someone explain me the right way how to do that?

this is a symbol :foo it's the same like "foo" right?

Also: if I got a form_tag(@something), why do I have to make brackets if I want to access html elements? like form_tag(@something, :html => {:foo => :bar})

Can someone explain it ?

thanks

marzapower
  • 5,531
  • 7
  • 38
  • 76
user3008711
  • 33
  • 1
  • 7

1 Answers1

4

The hash rocket => is the original way to build hashes. In later versions of Ruby they introduced a JSON-like colon-based syntax for cases where the key is a symbol. So :foo => :bar and foo: :bar are equivalent (and as David pointed out in the comment above, you had the colon on the wrong side of "foo" in your question.)

Using => is still the only way to define hashes for certain kinds of keys (See: Is Hash Rocket deprecated?). So when you are starting out, it can be good to just stick with => until you get a feel for the differences.

One other thing that can be confusing when you're new to Rails is that ActiveSupport provides an object called HashWithIndifferentAccess which treats :foo and "foo" as equivalent keys. This is not the case for a regular Ruby Hash object. So check the class of the object you are dealing with.

And the reason that :html options are in brackets is because that is a nested hash and makes it easy for someone to define a method like form_for and allow multiple multi-value inputs.

Community
  • 1
  • 1
cschroed
  • 6,304
  • 6
  • 42
  • 56