How to Validate the value of a form in Rails 3 - ruby-on-rails

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 like:
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.

Related

Rails 3 Active record validation error messages with unwanted/extra characters

I'm workin on ROR app using Rails 3.2.9 and I'm getting the error messages for a sign up page in my app as follows
<li>Login is too short (minimum is 3 characters)</li><li>Email is too short (minimum is 7 characters)</li><li>Email is invalid</li><li>Password can't be blank</li><li>Password is too short (minimum is 4 characters)</li><li>Password is invalid</li><li>Password confirmation can't be blank</li>
These are the default messages of Active Record Validation . (ref: http://guides.rubyonrails.org/active_record_validations_callbacks.html )
This app was previously written in Rails 2 and later migrated to rails 3. I have changed the validates_presence_of commands to validates : password , :presence=>true etc in accordance with rails 3 .
In the view ( signup.html.erb) error_messages_for is rendering these msgs. It is deprecated from rails 3.
Can anyone tell me what needs to be used instead of error_messages_for in the view and all code needs to be changed correspondingly for getting the error msgs right..
Here's the code (not complete)
user.rb in app/model
class User < ActiveRecord::Base
has_many :excel_files # One user may have many excel files
has_one :user_access_validity# One user may have one license period
# Virtual attribute for the unencrypted password
attr_accessor :password
attr_accessible :login
attr_accessible :email
attr_accessible :password
attr_accessible :password_confirmation
attr_accessible :company
#changes of 'validates' in accordance with rails 3:
validates :login, :presence => true,
:length => { :within => 3..40},
:uniqueness => { :case_sensitive => false },
:format => { :with => /^([a-z_0-9\.]+)$/i },
:on => :create,
:if => :is_login_entered?
validates :email, :presence => true,
:length => { :within => 7..100},
:uniqueness => { :case_sensitive => false },
:format => {:with => /^([a-z]+((\.?)|(_?))[a-z0-9]+#(mindtree.com|rvce.edu.in))$/i},
:on => :create,
:if => :is_email_entered?
validates :company, :presence => true,
:format => { :with =>/(mindtree|RVCE)/i},
:format => { :with => /^([a-z]+)$/i },
:on => :create,
:if => :is_company_entered?
#validates_presence_of :login, :email, :company
on => :create, :if => :is_login_entered?
validates :password, :presence => true,
:length => { :within => 4..40 },
:confirmation => true,
:format => { :with => /^([a-z0-9#!#\$]+)$/i },
:on => :create,
:if => :password_required?
validates :password_confirmation, :presence => { :if => :password_required? }
#validates_presence_of :password_confirmation, :if => :password_required?
before_save :encrypt_password
.
.
.
In signup.html.erb
<font color=red>(Fields marked * are mandatory)</font><h3>Sign me up!</h3>
<br>
<span class='error'><%= error_messages_for (#user) %></span>
<%= form_for :user do |f| -%>
<p><label for="login"><span class='redcolor'>*</span>Login</label><br/>
<%= f.text_field :login %></p>
<p><label for="email"><span class='redcolor'>*</span>Email</label><br/>
<%= f.text_field :email %></p>
<p><label for="password"><span class='redcolor'>*</span>Password</label><br/>
<%= f.password_field :password %></p>
<p><label for="password_confirmation"><span class='redcolor'>*</span>Confirm Password</label><br/>
<%= f.password_field :password_confirmation %></p>
<p><label for="company"><span class='redcolor'>*</span>Company</label><br/>
<%= f.text_field :company %></p>
<p><%= submit_tag 'Sign up' %></p>
<% end -%>
Solution
Got the following code from http://www.rubydoc.info/github/edavis10/redmine/ApplicationHelper:error_messages_for which shud be added in application_helper.rb and corresponding change in html.erb file as <%= error_messages_for (#user) %>
Code:
def error_messages_for(*objects)
html = ""
objects = objects.map {|o| o.is_a?(String) ? instance_variable_get("##{o}") : o}.compact
errors = objects.map {|o| o.errors.full_messages}.flatten
if errors.any?
html << "<div id='errorExplanation'><ul>\n"
errors.each do |error|
html << "<li>#{h error}</li>\n"
end
html << "</ul></div>\n"
end
html.html_safe
end
http://guides.rubyonrails.org/active_record_validations_callbacks.html
if you read this guide you will see that in you form you can use form.error_messages
Solution for the question is added below the question

Handling model requirements within the same view?

First and foremost, thanks for taking time to read and respond to my questions. I really appreciate it.
I'm not looking for the exact code on how to achieve the following but more of a direction or path I should follow.
Users that are logged in can create different courses. I've added a requirement (a provider) for each course and I want the user to have at least one provider associated (using rolify for this) to them before doing so but I'd like this to be on the same view (courses#new)
I've tried the following:
Nested forms (Doesn't work since I require at least one provider upon course creation)
Adding the providers#new in a modal on the page (can't call a controller from another one using form_form(#provier)
I've thought of the following:
Redirect the users to providers#new if they haven't created one first
Add a modal with a form_tag element that creates a provider and then refreshes the underlying page.
What are your thoughts? Better ideas?
Thanks!
Francis
My courses#new (_form) view
<%= simple_form_for(#course) do |f| %>
<%= f.error_notification %>
<%= f.input :name %>
<%= f.input :description, as: :text, input_html: { rows: '2' } %>
<%= f.association :provider, :value_method => :id, collection: Provider.with_role(:provider_admin, current_user), input_html: { class: 'input-large' }, include_blank: false %>
<div class="form-actions">
<%= f.button :submit, :class => 'btn-primary' %>
<%= link_to "Cancel", :back, class: 'btn' %>
</div>
<% end %>
models/provider.rb
class Provider < ActiveRecord::Base
attr_accessible :description, :name
validates :name, :presence => true
validates :description, :presence => true
validates :name, :length => { :minimum => 6, :maximum => 100 }
validates :description, :length => { :minimum => 6, :maximum => 100 }
has_many :courses
end
models/course.rb
class Course < ActiveRecord::Base
attr_accessible :description, :name, :provider_id
validates :name, :presence => true
validates :name, :length => { :minimum => 6, :maximum => 100 }
validates :description, :presence => true
validates :description, :length => { :minimum => 6, :maximum => 256 }
validates :provider_id, :presence => true
belongs_to :provider
has_many :sessions, :dependent => :destroy
end
I like the idea where you do a redirect in courses#new to providers#new when !current_user.provider.any?.
But I would probably go the nested forms way. You can use one form to create a new course and a new provider if a user doesn't have a provider. Have a look at http://railscasts.com/episodes/196-nested-model-form-revised to get a quick idea. I think that this would be best UI wise.

Showing error messages in active admin for has many relationship table

I am facing an issue showing up the error messages in active admin.
I get all the error messages displayed with the fields in the form.
But in the code below, I need atleast one skill and maximum 5 skills to be added.
Else need to throw an error message.
I've added a validation in model as :
validates :skills, :length => { :minimum => 1, :maximum => 5,
:message => " should be atleast 1 and less than 5"}
This validates perfectly, but no error message is displayed.
Can anyone help me with the display of the error message.
Following is the code :
form :html => { :enctype => "multipart/form-data" } do |f|
f.inputs "User", :multipart => true do
f.input :name
f.input :email, :as => :email
f.input :profile_name
f.input :date_of_birth
f.input :gender, :as => :select, :collection => Gender::GENDERS
end
f.inputs "Skills* ( minimum 1 & maximum 5 )" do
f.has_many :skills do |p|
if !p.object.nil?
# show the destroy checkbox only if it is an existing appointment
# else, there's already dynamic JS to add / remove new appointments
p.input :_destroy, :as => :boolean, :label => "Destroy?",
:hint => "Check this checkbox, if you want to delete this field."
end
p.input :description
p.input :title
end
end
end
end
activeadmin 0.5.1 is available on github.
it contains next line in changelog
"Add support for semantic errors #905 by #robdiciuccio"
here is pull request with this feature
https://github.com/gregbell/active_admin/pull/905
example
form do |f|
f.semantic_errors *f.object.errors.keys
f.inputs
f.inputs "Locations" do
f.has_many :locations do |loc|
loc.input :address
loc.input :_destroy, :as => :boolean, :label => "Delete"
end
end
f.buttons
end
to use it add to Gemfile
gem 'activeadmin', :git => "git://github.com/gregbell/active_admin.git", :tag => "v0.5.1"
For passing validation try this
validates_length_of :skills,
:within => 1..5,
:too_short => 'too short message',
:too_long => 'too long message'

form validation with simple_form and html5

The easy way from our page is
welcome-controller add an email -> second_controller create an new object with the E-Mailadddress.
we have a welcome-controller that shows our welcome-page. At this page you can type an e-mailaddress which will give to an other controller. We work with simple_form
If we that this config.browser_validations = false and enter an "normal" text we get an error on the create action. In the older version, without simple_form we get an validation-error.
If we enable this we get the html5 validation. but when the browser doesn't support html5?
Our model is here
validates :owner_email,
:presence => true,
:format => { :with => /\A[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]+\z/ },
:on => :create
Our welcome-view is here
<p>
<h2>Create a list without registration.</h2>
<%= simple_form_for([#list], :html => {:class => 'well' }) do |f| %>
<%= f.input :owner_email, :label => false, :placeholder => 'Your Email.' %>
<%= f.button :submit, "Create", :class => "btn-primary" %>
<% end %>
</p>
Our create-action from the second controller is this
def create
# create a new list and fill it up
# with some default values
#list = List.new(
:title => "List",
:description => "Beschreibung",
:owner_email => "test#domain.com",
:admin_key => generate_admin_key)
#list.update_attributes(params[:list])
respond_with(#list) do |format|
format.html {#
redirect_to :action => "admin", :id => #list.access_key, :status => 301}
end
end
What have we to change that we get errormessages in the html4 version? can everyone help us please?
Just add a :message parameter. Unless you changed simple_form configuration, message errors should be shown on the right side of the field with errors.
validates :owner_email,
:presence => true,
:format => { :with => /\A[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]+\z/ ,
:message => 'Invalid e-mail! Please provide a valid e-mail address'},
:on => :create

Translate form helper to simple_form or formstatic

I have this in my model:
class Person < ActiveRecord::Base
RELATIONSHIP_STATUSES = [
"single",
"in a relationship",
"together",
"it's complicated"
]
validates :relationship_status, :inclusion => RELATIONSHIP_STATUSES
end
This in the view:
collection_select(:person, :relationship_status, Person::RELATIONSHIP_STATUSES, :to_s)
And I would like to translate that to simple_form. Is that possible?
If I understood you right, it's simple(it's for formtastic):
<%= form.input :relationship_status, :as => :select, :collection => Person::RELATIONSHIP_STATUSES %>

Resources