How does Rails know the difference between these two identical expressions?
I am using a 4 year old Rails tutorial and I have Rails 4.0.2. I made a model called "Thing" and a controller called "Things". The Thing model has one attribute, Data. In my activity create
, I had this line:
@thing = Thing.new(params[:thing])
which leads to this error:
ActiveModel::ForbiddenAttributesError in ThingsController#create
I found a StackOverflow thread that said I needed require
my required parameters and it worked fine.
Before I looked, I tried to put the hash from my parameters directly into the method Thing.new()
and I didn't get an error. I started with this line:
puts params[:thing]
in my action create
typing "12345" in the textbox click submit and got this in the console:
{"data"=>"12345"}
So, I tried this in action create
:
@thing = Thing.new({"data" => "12345"})
and I didn't get the error. I even confirmed that they were identical by doing this:
puts params[:thing] == {"data"=>"12345"}
and I get "true" on the console. Thus,
Thing.new(params[:thing])
gives me error but
Thing.new({"data"=>"12345"})
not.
How can Rails tell the difference between these two arguments when they appear to be the same?
source to share
params[:thing]
are not the same as, {"data" => "12345"}
they have the same meaning when called on them inspect
, and the class params
overrides ==
to say it is equal to a hash.
Rails 4+ uses Strong Parameters , which is a security feature, to make sure you know what you are putting into your models. Basically, Rails wants to validate the parameters. It lets you do Thing.new({"data" => "12345"})
because you, the developer, are creating the Hash directly and are more trustworthy than anyone on the internet calling your server.
source to share