简体   繁体   中英

rails can't get symbol params

I have a model and this model has an attribute that name is status. Here is the validation for status;

validates_inclusion_of :status, :in => [:nil, :new, :old], :message => "......"

I create an edit form for my model and this is my select input;

 =f.select :status, [["New Record", :new], ["Old Record", :old]], {:include_blank => false}

When I submit the edit form, i can't get status as a symbol and getting error about this area.
When try to change status parameter with "to_sym" method then it works.

params[:my_model][:status] = params[:my_model][:status].to_sym

Why should I use this method ? Is there any way to send data as a symbol ?

The data received from your HTML form is always a string, and rails doesn't have any automatic transformation of these sorts of values into symbols. Generally keys are symbolized, not values.

I would recommend treating your values (eg :new, :old, etc) as strings and then things will be consistent. Note also that your datastore most likely cannot handle symbols without some sort of serialization (eg they will be converted to yaml).

Remember that even when you write in your rails views symbols all of it gets parsed to HTML as strings. HTTP has no notions of ruby symbols and therefore you cannot send data as a symbol.

When you get the parameters in your controller it is your responsibility to parse them to symbols if you are checking them against symbols.

What you get from params[:something] will always be a string. What is the datatype of status in your database?
I'm thinking you could just do

validates_inclusion_of :status, :in => [nil, "new", "old"], :message => "......"

In HTTP request there is no data types. The data is wrapped in query string or request body which is totally string.

Rails only parses that string and converts it into hash called 'params'. Each value of the key is string or file object based on the request. You never get an symbol as a value of hash key.

Try to use string like

'new', 'old'

So that you can avoid a function call to_sym

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM