Skipping before Create on particular controller al

2020-07-22 10:00发布

How to skip before_create on particular controller alone in rails

example

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

I want this to be skipped on this controller alone,

     class FriendsController < ApplicationController
          def new
          end
          def create
          end
     end

3条回答
Explosion°爆炸
2楼-- · 2020-07-22 10:48

It's a hack, but you could add a virtual attribute to the model class that simply acts as a flag to indicate whether the callback should run or not. Then the controller action can set the flag. Something like:

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

I'm not sure off the top of my head if the before_create callback's :unless option can refer directly to the name of a virtual attribute. If it can't then you can set it to a symbol that's the name of a method within your model and simply have that method return the skip_validation attribute's value.

查看更多
叼着烟拽天下
3楼-- · 2020-07-22 10:54

Use method which not calls the callbacks. such as save(false), update_attribute.

Something like following

 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

EDITED

Try this

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

&

@user.save(false)
查看更多
ゆ 、 Hurt°
4楼-- · 2020-07-22 11:00

Don't skip validation entirely with @user.save(false), unless that's the only thing you are validating is the email address.

You should really be moving this logic into your model with something like

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 contain compared to your other ones? Can you post your other controllers that you wouldn't like it to validate on and then we can compare it to this one.

查看更多
登录 后发表回答