user4827489
user4827489

Reputation:

before_create rule not working

In my user.rb model I have the following:

    before_create :check_name

    def check_name
        user = User.where(:name => self.name, :place => self.place)
        if user.present?
          p "ccccccccccccccccccccccccccccccccccccccccc"
          @error = "Same combination of name and place are already present"
          return @error
        end
      end

and in my controller:

    def create
        error_flag = false
        @user =User.new(user_params)
        if @user.save
          error_flag = true
          @success = I18n.t('user.success.user_created')
        else
          @error = find_error(@user)
        end

        respond_to do |format|
          format.js {
            render :layout => false,
                   :locals => {
                     :request => error_flag,
                     :user => @user
                   }
          }
        end
  end

My aim was to not create a user if the condition defined in the model is true, however the user is created anyway. Any ideas what I'm doing wrong?

Upvotes: 1

Views: 101

Answers (3)

Dinshaw Raje
Dinshaw Raje

Reputation: 963

You can do just a simple thing add this in your model:

validates_uniqueness_of :name, :scope => :place

and remove all the code i.e before_create and its method.

Upvotes: 0

Roman Kiselenko
Roman Kiselenko

Reputation: 44380

Your before_create callback in model do not adds error in the model. Use validate instead of before_create for add errors, then your records do not save to database and @user.save returned false:

validate :check_name

def check_name
   user = User.where(:name => self.name, :place => self.place)
   errors.add(:base, "Something wrong") if user.present?
end

if you want use before_create callback for add errors:

before_create :check_name

def check_name
   user = User.where(:name => self.name, :place => self.place)
   errors.add(:base, "Something wrong") if user.present?
end

More prefered uses validate for this case instead of before_create. and read how validate model and add errors.

Read how validate model and add errors.

Upvotes: 2

Hemali
Hemali

Reputation: 465

Yes. Before Create is just a callback which will be executed when you call User.save. But if you want to stop creation of records. you go with validation.Write your custom validation

validates_with :check_name

Upvotes: 0

Related Questions