简体   繁体   中英

Devise: Unable to limit model validation to specific def's

So I'm working on the registration aspect of the site currently. I have a main sign up which is just full name, email and password. (aka new.html.erb)

After you fill in that information I direct you to a new site (setup.html.erb) and ask for more info like city, country etc.

On that you also have the edit profile account.

I am trying to make my app more secure and adding restrictions and presence etc in the model. However how can I limit them.

Currently if I do validates :email, presence: true,
and I go to a form that doesn't even contain the email for nor permits it I get an error up that I need to add an email.

Also how do I fix this: I make presence true, I input require in html5. But still if I go to my source code and just remove the form and push submit it saves and I can bypass adding info.

Currently if I do validates :email, presence: true, and I go to a form that doesn't even contain the email for nor permits it I get an error up that I need to add an email.

Fix:

what you need is a conditional validation . If we look at rail guides it says

Sometimes it will make sense to validate an object only when a given predicate is satisfied. You can do that by using the :if and :unless options, which can take a symbol, a string, a Proc or an Array.

So in your model you could do something like:

class Order < ActiveRecord::Base
  validates :email, presence: true, if: :need_to_validate?

  def need_to_validate?
    #your condition to check whether you want email validation or not
  end
end

Update:

You can use params[:action] and params[:controller] smartly to check in which action and controller(hence which view) you currently are in so your method would be:

def need_to_validate?
  params[:action] == your_view_action && params[:controller] == your_controller_name     #your condition to check whether you want email validation or not
end

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