form validation with simple_form and html5 - ruby-on-rails

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

Related

Rails Form is being submitted automatically when I visit page

I have a rating form with 5 radios and a submit button in it. The problem is when I visit this page, for some reason it tries to submit the form (with 'zero' values, of course). Validations don't let to do this, so it renders error message, which is not pretty.
Rating form:
= simple_form_for #shop.ratings.find_or_create_by(user_id: user_id),
:html => {:id => form_id,
:class => "star_rating_form"} do |f|
= f.hidden_field :shop_id, :value => #shop.id
- if signed_in?
= f.hidden_field :user_id, :value => current_user.id
= f.input :stars,
:label => "",
:collection => [[1], [2], [3], [4], [5]],
:label_method => :last,
:value_method => :first,
:as => :radio_buttons,
:item_wrapper_class => 'inline',
:checked => true
= f.submit
Ratings controller:
class RatingsController < InheritedResources::Base
belongs_to :shop
actions :create, :update
def create
#shop = Shop.find(params[:rating][:shop_id])
super
end
def update
#shop = Shop.find(params[:rating][:shop_id])
super
end
private
def permitted_params
params.permit(:rating => [:stars])
end
I tried to do like super unless params[:rating][:stars] == 0 however, it didn't help.
PS For the rest the form works fine.
I am not sure but is this bcoz you are using find_or_create_by which is right away creating object, try find_or_initialize_by. Or look in javascript somewhere you specified function onload() { form.submit(); } is specified. Hope it may help

Rails: Spaces in string used for name causes validation error

I have a User Group table with a group_name value that is entered when the group is created. If there is a space in the group name, for example "Team Lol", the group name is still created, but it is not assigned to the current user, and it throws the error message in my if/else statement in the controller. Code is as follows:
Controller:
def create
#group = current_user.create_user_group(group_params)
current_user.user_group = #group
current_user.save
if #group.valid?
redirect_to '/user_groups/'+#group.group_name, :notice => "Your group has been created"
else
redirect_to '/user_groups/', :error => "Error: group name may already be taken. Search, or try a new name."
end
end
Model
class UserGroup < ActiveRecord::Base
has_many :users
has_secure_password
validates :password, :presence => true
validates :group_name, :presence => true, :uniqueness => true
before_validation :strip_blanks
def strip_blanks
self.group_name = self.group_name.strip
end
Create form:
<div class="form-group">
<label for="Group Name">Enter group name</label>
<%= f.input :group_name, :required => true, :autofocus => true, :maxlength => 40, :input_html => { :class => "form-control" }, :label => false, :placeholder => "Group name" %>
</div>
<div class="form-group">
<label for="Password">Password</label>
<%= f.input :password, :required => true, :autofocus => true, :maxlength => 40, :input_html => { :class => "form-control" }, :label => false, :placeholder => "Group password" %>
</div>
<%= f.button :submit, :class => "btn btn-md btn-warning" %>
</div>
I think it's because you are already creating the group in this line:
#group = current_user.create_user_group(group_params)
then, you're assigning (and Rails tries to create it again) here:
current_user.user_group = #group
current_user.save
I think you should remove the last two calls, given that if
#group = current_user.create_user_group(group_params)
succeeded, then the group is valid. The action that will follow is to redirect there.
Disclaimer: this is off the top of my head.
I just got it - it was a URI issue.
When a name with a space was created, the user was routed to /user_groups/The A Team.
It my routes I have /user_groups/:group_name routing to that group's home page.
However, since those spaces don't register correctly, the app seems to run another POST request to create a group instead.
I simply changed my redirect to redirect_to '/user_groups/'+#group.group_name.gsub(/\s/,'%20'), :notice => "Your group has been created"
Let me know if you think there's any problems with the way I handled this.
Thanks for everyones help,
Daniel

How save input from static page to database in rails

i want to save a input "email" from static pages to the database. Right now, i have a emails model with a :address field, but i can't save the value when click the submit input.
Layout with form
# layout/website.html.erb
<div>
<%= form_for #email, :url => newsletter_path, :method => :post do |email| %>
<%= email.text_field :address %>
<%= email.submit "Go" %>
<% end %>
</div>
Pages Controller
# controllers/pages_controller.rb
def home
newsletter
end
def newsletter
#email = Email.new(params[:address])
if #email.valid?
redirect_to(request.referer, :notice => "The suscription has been sent successfully.")
else
redirect_to(request.referer, :alert => "Please add an valid email address.")
end
end
Routes
# routes.rb from static pages
get "/home" => 'pages#home', :as => :home
get "/pricing" => 'pages#pricing', :as => :pricing
get "/logo-gallery" => 'pages#logo_gallery', :as => :logo_gallery
get "/blog" => 'pages#blog', :as => :blog
get "/blog/:id" => 'pages#post', :as => :post
get "/contact" => 'pages#contact', :as => :contact
match '/contact' => 'pages#create', :as => :contact, :via => :post
get "/faqs-and-terms" => 'pages#faqs_and_terms', :as => :faqs_and_terms
match "/newsletter" => 'pages#newsletter', :as => :newsletter, :via => :post
Model
# models/email.rb
class Email < ActiveRecord::Base
attr_accessible :address
validates :address, :format => { :with => %r{.+#.+\..+} }, :allow_blank => true
end
With this code, when visit /home right now i'm received:
ActionController::ActionControllerError in PagesController#home
Cannot redirect to nil!
I hope you can help me, what can i do to fix this and get a better code. Thank you.
You should use Email.create(params[:email]) instead of Email.new(params[:address]) to persist records in DB. Also, in your view you code add hidden_field
<%= email.text_field :address %>
<%= hidden_field_tag :referer, :value => request.path %>
<%= email.submit "Go" %>
And then in controller:
redirect_to params[:referer]
UPD
Also, please notice that you should use params[:email] in your controller, not params[:address]. You can invoke raise params.inspect in your controller to inspect params sent by form.
In newsletter action email record is only initialized but not saved. And you have no need to call newsletter method inside home action every time. Just update your code like this.
Pages Controller
# controllers/pages_controller.rb
.....
# no need to call newsletter action here
def home
end
def newsletter
#email = Email.new(params[:email])
if #email.save
redirect_to((request.referer || '/'), :notice => "The suscription has been sent successfully.")
else
redirect_to((request.referer || '/'), :alert => "Please add an valid email address.")
end
end
Layout with form
As #email is not defined in controller, so you should initialize an Email object in form.
# layout/website.html.erb
<div>
<%= form_for Email.new, :url => newsletter_path, :method => :post do |email| %>
<%= email.text_field :address %>
<%= email.submit "Go" %>
<% end %>
</div>
I hope that it should work.

Adding a custom action to Devise Registrations..Unknown Action Error

After Googling everywhere about how I can fix this I decided to post a question. I'm trying to add a custom action "create_pro" to the Devise Registrations controller so I can create a user with additional fields (A pro user). This form is on the same page as the devise create action for a user.
I keep getting the following error after submitting the form:
Unknown action
The action 'create_pro' could not be found for
Devise::RegistrationsController
How can I fix this?
Routes
devise_for :users,:controllers => { :registrations => "registrations" }
devise_scope :user do
post "gopro", :to => "devise/registrations#create_pro"
end
Registrations Controller
class RegistrationsController < Devise::RegistrationsController
before_filter :authenticate_user!, :only => :token
def new
super
end
def create
#user = User.new(params[:user])
if #user.save
sign_in #user
flash[:notice] = "Welcome to Banking Analytics."
redirect_to '/mybank'
else
render :action => :new
end
end
def create_pro
#user = User.new(params[:user])
if #user.save
sign_in #user
flash[:notice] = "Welcome to Banking Analytics."
redirect_to '/mybank'
else
render :action => :new
end
end
end
View
<div class="signup_form_basic">
<%= simple_form_for #user, :url => url_for(:controller => 'registrations', :action => 'create_pro') do |f| %>
<%= f.error_notification %>
<%= f.input :email, :required => true, :autofocus => true, :label => 'Username ( Your Email )', :placeholder => 'Email Address' %>
<%= f.input :password, :required => true, :autofocus => true, :label => 'Password', :placeholder => 'Password' %>
<%= f.input :password_confirmation, :required => true, :autofocus => true, :label => 'Confirm Password', :placeholder => 'Password Confirmation' %>
<%= f.button :submit, "Sign Up >>", class: 'btn btn-inverse' %>
<% end %>
</div>
I don't have an answer for the 'Unknown Action error' that you are facing, but I think the current solution is sub-optimal.
Since your goal is to have the following two classes of users
Pro-users, and
Regular (Non-pro) users,
it is probably best to follow the suggestion at How To: Customize routes to user registration pages and set up parallel structures for the two types of users.
That would be much more in line with the relationship between the two types of users.

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

Resources