Checking parameter types in Rails

I searched everywhere, and I am wondering if I am doing something wrong. And just to check, I will ask you guys!

So, I get paramsin a Rails controller. One pair key, value :status => true/false. However, I find that when I try to publish statusas a string, for example

:status => "THIS IS NOT A BOOLEAN"

and create my object in my controller, the attribute of :statusmy object will become false.

Therefore, is there any clean way in the rails to confirm that mine is :statuslogical?

Thank!

+4
source share
3 answers

This very strange method will trick

def is_boolean?(item)
  !!item == item
end

params[:status] = 'some string'
is_boolean?(params[:status])
# => false

params[:status] = true
is_boolean?(params[:status])
# => true

def is_boolean?(item)
  item == false || item == true
end
+3

@Iceman , , / , to_bool . iee

class String
   def to_bool
    return true if self == true || self =~ (/(true|t|yes|y|1)$/i)
    return false if self == false || self.blank? || self =~ (/(false|f|no|n|0)$/i)
    raise ArgumentError.new("invalid value for Boolean: \"#{self}\"")
   end
end

intializer .

 Mymodel.new(status: params[:status].to_s.to_bool)

to_s , nil '' incase status params.

+1

Validation

Rails, , ( ):

#app/models/model.rb
Class Model < ActiveRecord::Base
   validates :status, inclusion: { in: [true, false] }, message: "True / False Required!"
end

-

MVC

:

  • DRY
  • MVC

DRY, , . "Single Source Of Truth" , , /,

-, MVC (Model-View-Controller). MVC Rails , . - , (IE )

+1

All Articles