I have 2 forms in page which are as below and even i include the error printing sections those are not getting printed
<code>
<div id="tabs-2">
<% if #user.personal %>
<h2>Personal Details</h2>
<div class="image"><%= image_tag (#user.personal.avatar_url(:thumb))if #user.personal.avatar? %></div>
<b>First Name</b>: <%= #user.personal.first_name %><br>
<b>Middle Name</b>: <%= #user.personal.middle_name %><br>
<b>Last Name</b>: <%= #user.personal.last_name %><br>
<b>Date of Birth</b> <%= #user.personal.date_of_birth %><br>
<b>Gender</b>: <%= #user.personal.gender %><br>
<b>Category</b> <%= Category.find(#user.personal.category_id).category %><br>
<b>Blood Group</b>: <%= #user.personal.blood_group %><br>
<b>Fathers_name</b>: <%= #user.personal.fathers_name %><br>
<b>Mothers_name</b>: <%= #user.personal.mothers_name %><br>
<% else %>
<%= form_for([#user, Personal.new]) do |f| %>
<% if #user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#user.errors.count, "error") %> prohibited this candidate from being saved:</h2>
<ul>
<% #user.personal.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :first_name %><br/>
<%= f.text_field :first_name %>
</p>
<p>
<%= f.label :middle_name %><br/>
<%= f.text_field :middle_name %>
</p>
<p>
<%= f.label :last_name %><br/>
<%= f.text_field :last_name %>
</p>
<p>
<%= f.label :date_of_birth, "Date of Birth" %><br/>
<%= f.date_select :date_of_birth, start_year: 1985, end_year: 1999 %>
</p>
<p>
<%= f.label :gender %><br/>
<%= f.select :gender, options_for_select(%w[M F O]) %>
</p>
<p>
<%= f.label :blood_group %><br/>
<%= f.select :blood_group, options_for_select(%w[AB A+ B+ O ]) %>
</p>
<p>
<%= f.label :fathers_name %><br/>
<%= f.text_field :fathers_name %>
</p>
<p>
<%= f.label :mothers_name %><br/>
<%= f.text_field :mothers_name %>
</p>
<p>
<%= f.label :category_id %></br>
<%= select("personal", "category_id", Category.all.collect {|c| [c.category, c.id]}) %>
</p>
<p>
<%= f.label :avatar %>
<%= f.file_field :avatar %>
</p>
<p><%= f.submit "Submit", data: {confirm: "Are you sure information once submitted cant be modified ?"} %></p>
<% end %>
<% end %>
</code>
This is the first form this is getting in
app/views/user_dashboard/home.html.erb
I cant figure this out why the errors are not getting printed on failing the validations
present in personal.rb
class Personal < ActiveRecord::Base
# every personal information belongs to a particular user
belongs_to :user
# carrierwave uploader
mount_uploader :avatar, AvatarUploader
# validations
validates :first_name, presence: true, length: { maximum: 24}
validates :middle_name, length: { maximum: 24}
validates :last_name, presence: true, length: { maximum: 24}
validates :date_of_birth, presence: true
validates :gender, presence: true, length: { maximum: 1}
validates :category_id, presence: true
validates :blood_group, presence: true, length: { maximum: 2}
validates :fathers_name, presence: true, length: { maximum: 24}
validates :mothers_name, presence: true, length: { maximum: 24}
validates :avatar, presence: true
end
here is the personals_controller.rb
class PersonalsController < ApplicationController
before_action :set_personal, only: [:show, :edit, :update, :destroy]
# This helps to create personals
def create
#user = current_user
#personal = #user.create_personal(personal_params)
redirect_to home_path
end
private
# Never trust parameters from the scary internet, only allow the white list through.
def personal_params
params.require(:personal).permit(:user_id, :category_id, :avatar, :date_of_birth, :gender, :blood_group, :fathers_name, :mothers_name, :address_present, :first_name, :last_name, :middle_name)
end
end
and here are some logs
Started POST "/users/36/personals" for 127.0.0.1 at 2014-07-11 23:57:20 +0530
Started POST "/users/36/personals" for 127.0.0.1 at 2014-07-11 23:57:20 +0530
Processing by PersonalsController#create as HTML
Processing by PersonalsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"8qku1i/aIlz1aBdypnARzpiKuChWupPCMesjGoNmaTY=", "personal"=>{"first_name"=>"", "middle_name"=>"", "last_name"=>"", "date_of_birth(1i)"=>"1985", "date_of_birth(2i)"=>"7", "date_of_birth(3i)"=>"11", "gender"=>"M", "blood_group"=>"AB", "fathers_name"=>"", "mothers_name"=>"", "category_id"=>"1"}, "commit"=>"Submit", "user_id"=>"36"}
Parameters: {"utf8"=>"✓", "authenticity_token"=>"8qku1i/aIlz1aBdypnARzpiKuChWupPCMesjGoNmaTY=", "personal"=>{"first_name"=>"", "middle_name"=>"", "last_name"=>"", "date_of_birth(1i)"=>"1985", "date_of_birth(2i)"=>"7", "date_of_birth(3i)"=>"11", "gender"=>"M", "blood_group"=>"AB", "fathers_name"=>"", "mothers_name"=>"", "category_id"=>"1"}, "commit"=>"Submit", "user_id"=>"36"}
User Load (0.1ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 36 ORDER BY `users`.`id` ASC LIMIT 1
User Load (0.1ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 36 ORDER BY `users`.`id` ASC LIMIT 1
(0.1ms) BEGIN
(0.1ms) BEGIN
(0.1ms) ROLLBACK
(0.1ms) ROLLBACK
Personal Load (0.1ms) SELECT `personals`.* FROM `personals` WHERE `personals`.`user_id` = 36 LIMIT 1
Personal Load (0.1ms) SELECT `personals`.* FROM `personals` WHERE `personals`.`user_id` = 36 LIMIT 1
Redirected to http://localhost:3000/home
Redirected to http://localhost:3000/home
Completed 302 Found in 15ms (ActiveRecord: 0.4ms)
Completed 302 Found in 15ms (ActiveRecord: 0.4ms)
Started GET "/home" for 127.0.0.1 at 2014-07-11 23:57:20 +0530
Started GET "/home" for 127.0.0.1 at 2014-07-11 23:57:20 +0530
Processing by UserDashboardController#home as HTML
Processing by UserDashboardController#home as HTML
routes.rb
# http://www.quora.com/How-can-I-use-nested-routes-with-Devise
devise_for :users, :controllers => {:registrations => "registrations"}, :path => 'accounts'
# users has personal academics and applications hence nested routes
resources :users do
resources :personals
resources :academics
resources :applications
end
# user_dashboard controller
post 'user_dashboard/personal_creator'
# Controlpanel route
get 'controlpanels/controlpanel'
get 'controlpanels/resetranks'
get 'controlpanels/generateranks'
# verify routes
get 'vusers/verify'
# dashboard url shortening
match '/home', to: 'user_dashboard#home', via: 'get'
match '/controlpanel', to: 'controlpanels#controlpanel', via: 'get'
match '/verify', to: 'vusers#verify', via: 'get'
# routes for streams
resources :streams
# routes for categories
resources :categories
# routes for cutoffs
resources :cutoffs
There's a more cleaner way to do this. In your controller method(assuming it's home) you can do:
def home
#user = User.find(params[:id]) #your logic to find user
#personal = #user.build_personal #assuming you have user has_one personal association
end
and then in your form
<%= form_for([#user, #personal]) do |f| %>
<% if #personal.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#personal.errors.count, "error") %> prohibited this candidate from being saved:</h2>
<ul>
<% #personal.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<% end %>
Update:
In your create action(assuming this form takes to create action) you need to have something like this:
def create
#user = User.find(params[:id]) # logic to find user
#personal = #user.build_personal(personal_params)
respond_to do |format|
if #personal.save
format.html { redirect_to #personal }
else
format.html { render :action => "home" }
end
end
end
private
def personal_params
params.require(:personal).permit(:your_attributes)
end
Update:
If your form passes validations create_personal will simply create your record and in your case since it doesn't it will simply go to the step below it which is to redirect to home_path and hence no errors
You can even see it in your logs
User Load (0.1ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 36 ORDER BY `users`.`id` ASC LIMIT 1
(0.1ms) BEGIN
(0.1ms) BEGIN
(0.1ms) ROLLBACK
(0.1ms) ROLLBACK
Personal Load (0.1ms) SELECT `personals`.* FROM `personals` WHERE `personals`.`user_id` = 36 LIMIT 1
Personal Load (0.1ms) SELECT `personals`.* FROM `personals` WHERE `personals`.`user_id` = 36 LIMIT 1
Redirected to http://localhost:3000/home
class PersonalsController < ApplicationController
def create
#user = current_user
#personal = #user.build_personal(personal_params)
if #personal.save
flash[:notice] = "success"
else
flash[:alert] = #personal.errors.full_messages.each{|e|}
end
redirect_to home_path
end
end
Is this is the answer?
Related
I'm attempting to create a new oil production within the production information page. The fields are appearing but I am unable to get the oil production to save. Any help is appreciated
Productioninfos_controller.rb
def index
#productioninfos = Productioninfo.all
end
def new
#productioninfo = Productioninfo.new
end
def productioninfo_params
params.require(:productioninfo).permit(:firstproduction, :lastproduction, :numberofcompl, :totaldepth, :productionzone, oilproductioninfos_attributes: [:id, :oilcum, :avgbpmlastsixmonths, :avgbpodlastsixmonths])
end
Productioninfo.rb (model)
has_many :oilproductioninfos
accepts_nested_attributes_for :oilproductioninfo, :allow_destroy => :true, :reject_if => :blank
Oilproductioninfo.rb (model)
belongs_to :productioninfo
Productioninfos_form.html.erb
<%= f.fields_for :oilproductioninfos do |ff| %>
<div>
<%= ff.label :oilcum %>
<%= ff.text_field :oilcum %>
<%= ff.label :avgbpmlastsixmonths %>
<%= ff.text_field :avgbpmlastsixmonths %>
<%= ff.label :avgbpodlastsixmonths %>
<%= ff.text_field :avgbpodlastsixmonths %>
</div>
My user model contains values for things like:
name, email, phone, approved, etc..
The scope of the project I am working on includes custom user settings and for this reason I am using hstore (I dont want to create a user_settings table).
On the user edit view I want to create a checkbox called 'colors' and whether or not the checkbox is checked determines if that setting is set for the user or not.
I have already setup hstore as follows:
class AddHstore < ActiveRecord::Migration
def up
enable_extension :hstore
end
def down
disable_extension :hstore
end
end
And updated the User model as follows:
class AddSettingsToUser < ActiveRecord::Migration
def up
add_column :users, :settings, :hstore
end
def down
remove_column :users, :settings
end
end
This is essentially my user edit view:
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put, :class => "form-horizontal user" }) do |f| %>
<%= devise_error_messages! %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name, autofocus: true %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email %>
</div>
<div class="field">
<%= f.label :phone_number %><br />
<%= f.text_field :phone_number %>
</div>
<div class="actions">
<%= f.submit 'Update', :class => 'btn btn-primary' %>
</div>
<% end %>
At this point I am unsure as to how to actually implement this functionality. The user edit page allows the user to change their name, phone and other values but how would I include a new value for the hstore settings?
Inside the form_for from where you are creating users, add your hstore fileds like below :
<%= form_for resource, ...do |f| %>
#...
<%= f.fields_for :settings do |settings| %>
<%= settings.text_field :field1 %>
<%= settings.text_field :field2 %>
<% end %>
#....
<% end %>
Then update your controller strong parameter method like below to permit these new fields.:
def user_params
params.require(:user)
.permit(
:name,
:email,
settings: [ :field1, :field2 ]
)
end
Now, you are done. Open your rails console and try some sample data like
User.create(
settings: { field1: 'data1', field2: 'data2' }
)
I am using rails 4.1.6 I looked at the active record validations site and follow their direction, but nothing is displayed in the HTML even if there is an error.
However, when I do it in rails console it works.
post = Post.new #create an empty post to test
post.valid? #false
post.errors.messages #this is successfully generate the error message array
However, it doesn't display any error messages in HTML. In fact "#post.errors" doesn't even run
-Ruby code in html
<%= form_for #post, :method => :post do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.label :url %>
<%= f.text_field :url %>
<%= f.submit "Submit" %>
<% if #errors.any? %>
<ul>
<% #errors.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
<% end %>
-My PostsController
def create
# post = Post.new(title: params[:post][:title], url: params[:post][:url])
post = Post.new(post_params)
if post.save
redirect_to posts_path
else
#errors = post.errors.messages
redirect_to paths_path
end
end
private
def post_params
params.require(:post).permit(:title, :url)
end
-My post model
class Post < ActiveRecord::Base
validates :title, :length => {maximum: 140, minimum:1}, :presence => true
validates :title, :length => {maximum: 2083, minimum:1}, :allow_blank => true
end
When it comes to errors I do like to have a partial so I can keep my errors the same in the whole app like so:
app/views/shared/_errors.html.erb:
<% if object.errors.any? %>
<h5>The <%= t("activerecord.models.#{object.class.to_s.downcase}") %> could not be saved due to the following errors:</h5>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
And then for the views you want the errors to be displayed, just call:
<%= render 'shared/errors', object: #your_object %>
Hope this helps!
thanks for your help. Got some tip from my teacher it work. Simply use flash[:message] and it worked. Sorry for the trouble everyone
-My controller code
def create
post = Post.new(post_params)
if post.save
redirect_to :back
else
flash[:message] = post.errors.messages
redirect_to :back
end
end
-My HTML code
<%= simple_form_for #post, :method => :post do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.label :url %>
<%= f.text_field :url %>
<%= f.submit "Submit" %>
<%= flash[:message] %>
<% end %>
I'm making a single page application based on Futureme.org for practice. The user goes to the home page, sees a form to put their email address, subject, and the body of their message and sends it.
The problem I am having is I get an error "First argument in form cannot contain nil or be empty". Here is my code;
Model;
class Letter < ActiveRecord::Base
VALID_EMAIL_REGEX = /\A[\w+\-,]+#[a-z\d\-.]+\.[a-z]+\z/i
validates_presence_of :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates_length_of :subject, presence: true, length: { maximum: 50 }
validates_presence_of :message
end
Controller;
class LettersController < ApplicationController
def new
#letter = Letter.new
end
def create
#letter = Letter.new(params[:letter])
if #letter.save
redirect_to letters_path, :notice => "Your letter was sent!"
else
render "new"
end
end
end
View form;
<%= form_for #letter, :html => {:class => 'form-horizontal'} do |f| %>
<% if #letter.errors.any? %>
<div class="error_messages">
<h2><%= pluralize(#letter.errors.count, "error")%>stopped this message from being saved</h2>
<ul>
<% #letter.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.label :subject %><br />
<%= f.text_field :subject %><br />
</div>
<div class="field">
<%= f.label :message, "Message" %><br />
<%= f.text_area :message, size: "60x10" %>
</div>
<div class="actions"><%= f.submit "Submit", class: "btn btn-small btn-primary" %></div>
<% end %>
The form is on the home page which is in the "Welcome Controller".
Any help would be great.
It looks like you build letter in action new when form is drawn on other view :)
You should move #letter = Letter.new to appropriate action
One of the variant is:
#WelcomeController
def home
#letter = Letter.new
end
#LettersController
def create
#letter = Letter.new(params[:letter])
if #letter.save
redirect_to letters_path, :notice => "Your letter was sent!"
else
render "welcome/home"
end
end
be careful if you prepare some data in action home you should care about initializing them for action create when validation failed because you render "welcome/home" view
My form is:
<%= form_for #setup_limo, :html => { :class => 'form-horizontal' } do |f| %>
<%= render 'Partials/errors', object: #setup_limo %>
<div class="control-group">
<%= f.label :car_type_id, :class => 'control-label' %>
<div class="controls">
<%= f.collection_select :car_type_id,CarType.all,:id,:name, :class => 'text_field' %>
</div>
</div>
<div class="control-group">
<%= f.label :car_id, :class => 'control-label' %>
<div class="controls">
<%= f.collection_select :car_id,Car.all,:id,:name, :class => 'text_field' %>
</div>
</div>
<div class="control-group">
<%= f.label :driver_id, :class => 'control-label' %>
<div class="controls">
<%= f.collection_select :driver_id,Driver.all,:id,:name, :class => 'text_field' %>
</div>
</div>
<div class="form-actions">
<%= f.submit nil, :class => 'btn btn-primary' %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")),
setup_limos_path, :class => 'btn' %>
</div>
<% end %>
My Model is:
class SetupLimo < ActiveRecord::Base
belongs_to :user
belongs_to :car_type
belongs_to :car
belongs_to :driver
validates :user,:car_type,:car, :driver, :presence => :true
validates_uniqueness_of :driver, :scope =>[:user, :car_type, :car]
end
My controller permitted params:
def setup_limo_params
params.require(:setup_limo).permit(:car_type_id, :car_id, :driver_id, :user_id)
end
Create action:
def create
#setup_limo = SetupLimo.new(setup_limo_params)
respond_to do |format|
if #setup_limo.save
format.html { redirect_to #setup_limo, notice: 'Setup limo was successfully created.' }
format.json { render action: 'show', status: :created, location: #setup_limo }
else
format.html { render action: 'new' }
format.json { render json: #setup_limo.errors, status: :unprocessable_entity }
end
end
end
But on create i got error: The log is:
Started POST "/setup_limos" for 127.0.0.1 at 2013-08-09 21:02:05 +0530
Processing by SetupLimosController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"######=", "setup_limo"=>{"car_type_id"=>"3", "driver_id"=>""}, "commit"=>"Create Setup limo"}
[1m[35mCACHE (0.0ms)[0m SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1 [["id", 1]]
[1m[36mCarType Load (0.4ms)[0m [1mSELECT `car_types`.* FROM `car_types` WHERE `car_types`.`id` = 3 ORDER BY `car_types`.`id` ASC LIMIT 1[0m
[1m[35m (0.3ms)[0m ROLLBACK
Completed 500 Internal Server Error in 482ms
NoMethodError (undefined method `attributes' for nil:NilClass):
app/controllers/setup_limos_controller.rb:35:in `block in create'
app/controllers/setup_limos_controller.rb:34:in `create'
Rendered /Users/MohammedSha/.rvm/gems/ruby-2.0.0-p195/gems/actionpack-4.0.0.rc2/lib/action_dispatch/middleware/templates/rescues/_source.erb (1.1ms)
Rendered /Users/MohammedSha/.rvm/gems/ruby-2.0.0-p195/gems/actionpack-4.0.0.rc2/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.7ms)
Rendered /Users/MohammedSha/.rvm/gems/ruby-2.0.0-p195/gems/actionpack-4.0.0.rc2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (2.0ms)
Rendered /Users/MohammedSha/.rvm/gems/ruby-2.0.0-p195/gems/actionpack-4.0.0.rc2/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (42.6ms)
I'm using Rails 4
On submitting i got the above error,
I want to validate uniqueness of driver for user, car_type and car
Thanks for any help..
Maybe I'm missing something in the description, but you have a presence validation on driver and it is empty in the passed params.
If a driver can be empty, then drop it from that validation on SetupLimo:
validates :user, :car_type, :car, :presence => :true