Skipping before Create on particular controller alone in rails
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
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.
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)
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.
精彩评论