Skip before creation only on a specific controller in rails

How to skip before_create only on a specific controller in rails

Example

     class User < ActiveRecord::Base
        before_create :validate_email
        def validate_email
            ----
        end
     end

I want this to be skipped only on this controller,

     class FriendsController < ApplicationController
          def new
          end
          def create
          end
     end
+3
source share
3 answers

This is a hack, but you can add a virtual attribute to the model class, which simply acts as a flag to indicate whether the callback should work or not. Then the action of the controller can set the flag. Sort of:

class User < ActiveRecord::Base   
  before_create :validate_email, :unless => :skip_validation
  attr_accessor :skip_validation 

  def validate_email 
    ...
  end 
end 

class FriendsController < ApplicationController          
  def create          
    @user = User.find # etc...
    @user.skip_validation = true
    @user.save
  end          
end

, before_create callback :unless . , , skip_validation.

+2

, . save (false), update_attribute.

-

 class FriendsController < ApplicationController
      def new
      end
      def create
        @user=User.new({:email => "some_email@some_domail.com" })
        @user.save(false)  @this will skip the method "validate_email"
      end
 end

 class User < ActiveRecord::Base
    def validate
        ----
    end
 end

&

@user.save(false)
0

@user.save(false), , , .

-

before_create :validate_email, :if => :too_many_friends

def too_many_friendships
  self.friends.count > 10
end

What logic or difference in functionality does this controller make compared to others? Can you post your other controllers that you don't like to test them, and then we can compare them to this.

0
source

Source: https://habr.com/ru/post/1747337/


All Articles