简体   繁体   中英

validates inclusion in Rails not taking action

my Role class looks like this:

class Role < ApplicationRecord
  rolify :role_cname => 'Permission'
  has_and_belongs_to_many :users, :join_table => :users_roles
  
  departmentsNames = Institution.find(1).departments
  rolesPrefix = ['super_']
  departmentsNames.each do |departmentsName|
    rolesPrefix.push(departmentsName.department_short)
  end
  validates_uniqueness_of :name
  validates :name, inclusion: { in : rolesPrefix, message: "not a valid Role Prefix"}

  belongs_to :resource,
             :polymorphic => true,
             :optional => true    
  validates :resource_type,
            :inclusion => { :in => Rolify.resource_types },
            :allow_nil => true
  scopify
end

rolesPrefix is: => ["super_", "AUG", "CHI", "INN", "NCH", "PAL"]

but why im still be able to do something like this?

role = Role.create(name: "should_not_be_eccepted")

but why im still be able to do something like this?

 role = Role.create(name: "should_not_be_eccepted")

The validation is failing. create always returns an object, but when validation fails no exception is raised. It just isn't saved. From the docs...

Creates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not.

role.id should be nil. role.valid? should be false. role.errors.details should contain the validation error.


Get into the habit of using create! instead. create! will throw an exception on validation error which cannot be ignored. Also update! and save! .

create , save , and update are appropriate when you need to examine the validation errors. For example, in a controller...

  def create
    @client = Client.new(params[:client])
    if @client.save
      redirect_to @client
    else
      # This line overrides the default rendering behavior, which
      # would have been to render the "create" view.
      render "new"
    end
  end

The new template can use the validation errors in @client to populate its form with instructions about what went wrong and how to fix it.

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