开发者

How to Validate the value of a form in Rails 3

I'm trying to validate the value of a form (a checkbox actually) in a model, but am having a lot of trouble finding what to pass validates:

  validates :agreement, :agreement => true

I've gotten other things to work li开发者_StackOverflow中文版ke:

  validates :password, :presence => true, :length => {:minimum => 6, :maximum => 25}, :confirmation => true

My view looks like this:

        <% form_for :signup_form, :url => {:controller => "user", :action => "post_signup"} do |f| %>

... <%= f.check_box( :agreement ) %> I agree to the <%= link_to("Terms of Service", :controller=> "about", :action => "terms") %> and <%= link_to("Privacy Policy", :controller=> "about", :action => "privacy") %> ...

Which then goes to my controller:

    agreement = params[:signup_form][:agreement]

new_user = User.create(:login_name => login_name, :first_name => first_name, :last_name => last_name, :email => email, :password => password, :agreement => agreement, :created_at => DateTime.now())

And then my model.

Thanks for any help you can offer in advance.


You might be looking for :acceptance => true or validates_acceptance_of


You'll want to display your errors on the page, and ensure your validation is working at all. I would re-implement your validation as:

 # app/models/user.rb
 class User < ActiveRecord::Base
   validates :agreement do |ag|
     ag.errors.add "Must agree to the terms" unless self.agreement
   end

 end

see http://asciicasts.com/episodes/211-validations-in-rails-3 for a comprehensive treatment, including a nice way to display the errors.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜