Error on validation if dropdown is blank - ruby-on-rails-4

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

Related

Can't route to /logout with Authlogic

I've been trying to set up user authentication in my app using Authlogic, and I'm sure the problem is in my code but I can't seem to find it. When I hit the /login link, all works as expected, but my /logout wants to use GET instead of DELETE.
routing.db
Rails.application.routes.draw do
root 'comments#index'
resources :roles
resources :subjects
resources :comments
resources :topics
resources :users
resources :user_sessions, only: [:create, :destroy]
delete '/logout', to: 'user_sessions#destroy', as: :logout
get '/login', to: 'user_sessions#new', as: :login
end
user_sessions_controller
class UserSessionsController < ApplicationController
before_filter :require_no_user, :only => [:new, :create]
before_filter :require_user, :only => :destroy
def new
#user_session = UserSession.new
end
def create
#user_session = UserSession.new(user_session_params)
if #user_session.save
flash[:success] = "Welcome back!"
redirect_to root_path
else
render :action => :new
end
end
def destroy
current_user_session.destroy
flash[:success] = "Goodbye!"
redirect_to root_path
end
private
def user_session_params
params.require(:user_session).permit(:username, :password, :remember_me)
end
end
application.html.erb
<!DOCTYPE html>
<html>
<head>
<title><%= content_for?(:title) ? yield(:title) : "Untitled" %></title>
<%= stylesheet_link_tag "application" %>
<%= javascript_include_tag :defaults %>
<%= csrf_meta_tag %>
<%= yield(:head) %>
</head>
<body>
<div id="user_nav">
<% if current_user %>
<span><%= current_user.username %></span>
<%= link_to "Edit profile", edit_user_path(:current) %>
<%= link_to 'Sign Out', logout_path, :method => :delete %>
<% else %>
<%= link_to "Register", new_user_path %>
<%= link_to 'Sign In', login_path %>
<% end %>
</div>
<div id="container">
<% flash.each do |name, msg| %>
<%= content_tag :div, msg, :id => "flash_#{name}" %>
<% end %>
<%= content_tag :h1, yield(:title) if show_title? %>
<%= yield %>
</div>
</body>
</html>
Does anything here look wrong? Here's the error I'm getting:
In your application.html.erb file:
Change:
<%= javascript_include_tag :defaults %>
To:
<%= javascript_include_tag "application" %>
It should work after that!

rails 4 stripe payment causing line item invalid error

Like others working with Stripe payments, I was getting an error 'Cannot charge a customer that has no active card'. The form was not appending the token because the javascript did not have a matching id in the form, but now I am getting an rails error and the card is not being charged, the customer is created, the error states that there is an invalid line item, when the code to create the customer and charge the card is not run the order is created without error.
Order View
<script type="text/javascript" src="https://js.stripe.com/v2/">
$(function(){
Stripe.setPublishableKey('<%= Rails.configuration.stripe[:PUBLISHABLE_KEY] %>');
});
</script>
<div class = "Power Me" >
<fieldset>
<legend> Please enter your details </legend>
<%= render 'form', object: #object %>
</fieldset>
</div>
Rendered Order Form
<%= form_for(#order, :html => {:id => 'payment-form'}) do |f| %>
<% if #order.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#order.errors.count, "error") %> prohibited this order from being saved:</h2>
<ul>
<% #order.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= "Order Total: #{order_total.to_s}" %>
<%= "Order Currency: #{order_currency.to_s}" %>
</div>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :Address_line_1 %><br>
<%= f.text_area :address_line_1 %>
</div>
<div class="field">
<%= f.label :Address_Line_2 %><br>
<%= f.text_area :address_line_2 %>
</div>
<div class="field">
<%= f.label :City %><br>
<%= f.text_area :address_city %>
</div>
<div class="field">
<%= f.label :Region %><br>
<%= f.text_area :address_state %>
</div>
<div class="field">
<%= f.label :Postcode %><br>
<%= f.text_area :address_zip %>
</div>
<div class="field">
<%= f.label :Country %><br>
<%= f.select :address_country, Order::CC_COUNTRIES, prompt: 'Select the country' %>
</div>
<div class="field">
<%= f.label :email %><br>
<%= f.text_field :email, :placeholder => "you#example.com" %>
</div>
<div class="field">
<%= f.label :Payment_Type %><br>
<%= f.select :pay_type, Order::PAYMENT_TYPES, prompt: 'Select a payment method' %>
</div>
<div class="form-row">
<label>Card Number</label>
<input type="text" size="20" autocomplete="off" data-stripe="number" id="number" class="credit-number", placeholder = "**** **** **** ****" pattern="[\d ]*" />
</div>
<div class="form-row">
<label>Security Code/CVC</label>
<input type="text" size="4" autocomplete="off" data-stripe="cvc" id="cvc" class="credit-scurity" placeholder="***" pattern="\d*" />
</div>
<div class="form-row">
<label>Expiration (MM/YYYY)</label>
<input type="text" size="2" data-stripe="exp-month" id="exp-month" class="card-expiry-month" placeholder="MM" pattern="\d*" />
<span> / </span>
<input type="text" size="4" data-stripe="exp-year" id="exp-year" class="card-expiry-year" placeholder="YYYY" pattern="\d*" />
</div>
<div class="actions">
<%= f.submit 'Pay', :class =>"stripe-button" %>
</div>
<% end %>
orders model
class Order < ActiveRecord::Base
# attr_accessor :stripeToken
PAYMENT_TYPES = ["credit card"]
CC_COUNTRIES = ["United Kingdom", "France", "Italy"]
validates :name, :address_line_1, :address_zip, :email, presence: true
# validates :pay_type, inclusion: PAYMENT_TYPES
has_many :line_items, dependent: :destroy
def add_line_items_from_cart(cart)
cart.line_items.each do |item|
item.cart_id = nil
line_items << item
end
end
end
Orders Controller
class OrdersController < ApplicationController
include CurrentCart
before_action :set_cart, only: [:new, :create]
before_action :set_order, only: [:show, :edit, :update, :destroy]
# GET /orders
# GET /orders.json
def index
#orders = Order.all
end
# GET /orders/1
# GET /orders/1.json
def show
end
# GET /orders/new
def new
if #cart.line_items.empty?
redirect_to store_url, notice: "Your cart is empty"
return
end
#order = Order.new
end
# GET /orders/1/edit
def edit
end
# POST /orders
# POST /orders.json
def create
#order = Order.new(order_params)
#order.add_line_items_from_cart(#cart)
respond_to do |format|
if #order.save
Cart.destroy(session[:cart_id])
session[:cart_id] = nil
format.html { redirect_to #order, notice: 'Order was successfully created.' }
format.json { render action: 'show', status: :created, location: #order }
else
format.html { render action: 'new' }
format.json { render json: #order.errors, status: :unprocessable_entity }
end
end
Stripe.api_key = "sk_test_BsdqHq0SQuPqHIsm46lcpX4v"
#amount = order_total.to_i * 100
token = params[:stripeToken]
=begin
begin
customer = Stripe::Customer.create(
:email => order_params[:email]
)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => #amount, # amount in cents, again
:currency => order_currency,
:card => token,
:description => order_params[:email]
)
redirect_to root_path
rescue Stripe::CardError => e
#error = e
end
=end
end
# PATCH/PUT /orders/1
# PATCH/PUT /orders/1.json
def update
respond_to do |format|
if #order.update(order_params)
format.html { redirect_to #order, notice: 'Order was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #order.errors, status: :unprocessable_entity }
end
end
end
# DELETE /orders/1
# DELETE /orders/1.json
def destroy
#order.destroy
respond_to do |format|
format.html { redirect_to orders_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_order
#order = Order.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def order_params
params.require(:order).permit(:name, :email, :pay_type, :address_line_1, :address_line_2, :address_city, :address_state, :address_zip, :address_country)
end
end
My Application Helper
module ApplicationHelper
def order_total
total = LineItem.joins(:product).select("sum(line_items.quantity * products.price) as total").where("cart_id = ?", session[:cart_id]).first.total
end
def order_currency
currency = LineItem.joins(:product).joins(:currency).select("currencies.name as iso_name").where("cart_id = ?", session[:cart_id]).first.iso_name
end
# Returns the full title on a per-page basis.
def full_title(page_title)
base_title = "Ruby on Rails Tutorial Sample App"
if page_title.empty?
base_title
else
"#{base_title} | #{page_title}"
end
end
def bootstrap_class_for flash_type
{ success: "alert-success", error: "alert-danger", alert: "alert-warning", notice: "alert-info" }[flash_type] || flash_type.to_s
end
def flash_messages(opts = {})
flash.each do |msg_type, message|
concat(content_tag(:div, message, class: "alert #{bootstrap_class_for(msg_type)} fade in") do
concat message
end)
end
nil
end
# before filters
def signed_in_user
unless signed_in?
store_location
redirect_to signin_url, notice: "Please sign in."
end
end
def correct_user
#user = User.find(params[:id])
redirect_to(root_url) unless current_user?(#user)
end
def admin_user
redirect_to(root_url) unless current_user.admin?
end
end
Orders.js
$('#payment-form').submit(function(event) {
var form = $(this);
form.find('button').prop('disabled', true);
Stripe.createToken(form, stripeResponseHandler);
return false;
});
Working Order Form below, you cannot pass fields to Stripe and use them in the rails form to save in the db, its either or (previous example attempted to save address fields in the db and pass them to stripe as part of the transaction validation.
<%= form_for(#order, :html => {:id => 'payment-form'}) do |f| %>
<% if #order.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#order.errors.count, "error") %> prohibited this order from being saved:</h2>
<ul>
<% #order.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= "Order Total: #{order_total.to_s}" %>
<%= "Order Currency: #{order_currency.to_s}" %>
</div>
<div class="form-row">
<label>Full Name</label>
<input type="text" size="20" autocomplete="off" data-stripe="name" />
</div>
<div class="field">
<%= f.label :email %><br>
<%= f.text_field :email, :placeholder => "you#example.com" %>
</div>
<div class="field">
<%= f.label :Payment_Type %><br>
<%= f.select :pay_type, Order::PAYMENT_TYPES, prompt: 'Select a payment method', :selected => "credit card" %>
</div>
<div class="form-row">
<label>Address Line 1</label>
<input type="text" size="20" autocomplete="off" data-stripe="address_line1" />
</div>
<div class="form-row">
<label>Address Line 2</label>
<input type="text" size="20" autocomplete="off" />
</div>
<div class="form-row">
<label>Address City</label>
<input type="text" size="20" autocomplete="off" />
</div>
<div class="form-row">
<label>Address State</label>
<input type="text" size="20" autocomplete="off" />
</div>
<div class="form-row">
<label>Zip/Postcode</label>
<input type="text" size="20" autocomplete="off" data-stripe="address_zip" />
</div>
<div class="form-row">
<label>Country</label>
<input type="text" size="20" autocomplete="off" data-stripe="address_country" />
</div>
<div class="form-row">
<label>Card Number</label>
<input type="text" size="20" autocomplete="off" data-stripe="number" placeholder = "**** **** **** ****" pattern="[\d ]*" />
</div>
<div class="form-row">
<label>Security Code/CVC</label>
<input type="text" size="4" autocomplete="off" data-stripe="cvc" placeholder="***" pattern="\d*" />
</div>
<div class="form-row">
<label>Expiration (MM/YYYY)</label>
<input type="text" size="2" data-stripe="exp-month" placeholder="MM" pattern="\d*" />
<span> / </span>
<input type="text" size="4" data-stripe="exp-year" placeholder="YYYY" pattern="\d*" />
</div>
<div class="actions">
<%= f.submit 'Pay', :class => "button" %>
</div>
<% end %>
The form required the id referenced inthe javascript below
var stripeResponseHandler = function(status, response) {
var $form = $('#payment-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// token contains id, last4, and card type
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
// and re-submit
$form.get(0).submit();
}
};
jQuery(function($) {
$('#payment-form').submit(function(e) {
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
});
Order Model, fields removed
class Order < ActiveRecord::Base
PAYMENT_TYPES = ["credit card"]
CC_COUNTRIES = ["United Kingdom", "France", "Italy"]
validates :email, presence: true
validates :pay_type, inclusion: PAYMENT_TYPES
has_many :line_items, dependent: :destroy
def add_line_items_from_cart(cart)
cart.line_items.each do |item|
item.cart_id = nil
line_items << item
end
end
end
Application header
<!DOCTYPE html>
<html>
<head>
<title><%= full_title(yield(:title)) %></title>
<%= stylesheet_link_tag "application", media: "all",
"data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
$(function(){
Stripe.setPublishableKey('<%= Rails.configuration.stripe[:publishable_key] %>');
});
</script>
<%= csrf_meta_tags %>
<%= render 'layouts/shim' %>
</head>
<body>
Order Controller
class OrdersController < ApplicationController
include CurrentCart
before_action :set_cart, only: [:new, :create]
before_action :set_order, only: [:show,:edit, :update, :destroy]
# before_action :admin_user, only: [:destroy, :show]
# GET /orders
# GET /orders.json
def index
#orders = Order.all
end
# GET /orders/1
# GET /orders/1.json
def show
end
# GET /orders/new
def new
if #cart.line_items.empty?
redirect_to store_url, notice: "Your cart is empty"
return
end
#order = Order.new
end
# GET /orders/1/edit
def edit
end
# POST /orders
# POST /orders.json
def create
begin
#order = Order.new(order_params)
#order.add_line_items_from_cart(#cart)
Stripe.api_key = "sk_test_xxxxxxxxxxxxxxx"
#amount = order_total.to_i * 100
token = params[:stripeToken]
# Create a Customer
customer = Stripe::Customer.create(
:description => order_params[:email],
:card => token,
)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => #amount, # amount in cents, again
:currency => order_currency,
# :card => token,
:description => order_params[:email]
)
respond_to do |format|
if #order.save
puts "saving now"
Cart.destroy(session[:cart_id])
session[:cart_id] = nil
format.html { redirect_to #order, notice: 'Order was successfully created.' }
format.json { render action: 'show', status: :created, location: #order }
else
format.html { render action: 'new' }
format.json { render json: #order.errors, status: :unprocessable_entity }
end
end
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to root_path
end
end
# PATCH/PUT /orders/1
# PATCH/PUT /orders/1.json
def update
respond_to do |format|
if #order.update(order_params)
format.html { redirect_to #order, notice: 'Order was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #order.errors, status: :unprocessable_entity }
end
end
end
# DELETE /orders/1
# DELETE /orders/1.json
def destroy
#order.destroy
respond_to do |format|
format.html { redirect_to orders_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_order
#order = Order.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def order_params
params.require(:order).permit(:email, :pay_type)
end
end

accepts_nested_attributes_for not creating attr writer method

my guarantors model has_many addresses as :addressable and accepts nested attributes for addresses. however, when whitelisting the address attributes, the params hash isn't recognizing addresses_attributes: [:street, :city, etc.]. I keep getting unpermitted parameters addresses. anyone have trouble with this?
my models:
class UserApplication < ActiveRecord::Base
belongs_to :user
has_many :guarantors, dependent: :destroy
accepts_nested_attributes_for :guarantors
end
class Guarantor < ActiveRecord::Base
has_many :addresses, :as => :addressable, dependent: :destroy
belongs_to :user_application, :foreign_key => :user_application_id
accepts_nested_attributes_for :addresses
end
class Address < ActiveRecord::Base
belongs_to :addressable, :polymorphic => true
end
from the UserApplications Controller
def user_application_params
params.require(:user_application).permit(...,
guarantors_attributes: [:id, :fname, :lname, :relationship, :phone, :email, :user_application_id,
addresses_attributes: [:id, :street, :street_2, :unit, :city, :state, :zip, :addressable_id, :addressable_type]]
)
end
the 'nested' part of the form:
<%= f.fields_for :guarantors do |builder| %>
<div class="row">
<div class="col-md-1">
<h6>FIRST NAME</h6>
<%= builder.text_field :fname, :class => "form-control" %>
</div>
<div class="col-md-2">
<h6>LAST NAME</h6>
<%= builder.text_field :lname, :class => "form-control" %>
</div>
<div class="col-md-2">
<h6>RELATIONSHIP</h6>
<%= builder.text_field :relationship, :class => "form-control" %>
</div>
<div class="col-md-2">
<h6>PHONE</h6>
<%= builder.number_field :phone, :class => "form-control" %>
</div>
<div class="col-md-2">
<h6>EMAIL</h6>
<%= builder.text_field :email, :class => "form-control" %>
</div>
</div>
<%= f.fields_for :addresses do |builder| %>
<div class="col-md-1">
<h6>ADDRESS</h6>
<%= builder.text_field :street, :class => "form-control" %>
</div>
<div class="col-md-2">
<h6>ADDRESS 2</h6>
<%= builder.text_field :street_2, :class => "form-control" %>
</div>
<div class="col-md-2">
<h6>CITY</h6>
<%= builder.text_field :city, :class => "form-control" %>
</div>
<div class="col-md-2">
<h6>STATE</h6>
<%= builder.text_field :state, :class => "form-control" %>
</div>
<div class="col-md-2">
<h6>ZIP</h6>
<%= builder.number_field :zip, :class => "form-control" %>
</div>
</div>
<% end %>
<% end %>
Finally, params:
"guarantors_attributes"=>{"0"=>{"fname"=>"blah", "lname"=>"", "relationship"=>"", "phone"=>"", "email"=>"", "id"=>"68"}, "1"=>{"fname"=>"", "lname"=>"", "relationship"=>"", "phone"=>"", "email"=>"", "id"=>"69"}}, "addresses"=>{"street"=>"", "street_2"=>"", "city"=>"", "state"=>"", "zip"=>""}, ...
I keep getting unpermitted parameters addresses and it's also not nested within guarantors_attributes. Any ideas? Thanks in advance.
When you build your fields_for :addresses, I think you want that to be builder.fields_for since addresses are nested under guarantors.
f.fields_for :guarantors do |builder|
# fields
builder.fields_for :addresses do |builder|
# fields
end
end
code clarity
I would also make the block names more specific, since having 2 builder variables is confusing as to which scope you are in.
f.fields_for :guarantors do |guarantor_form|
# fields
guarantor_form.fields_for :addresses do |address_form|
# fields
end
end

No froms errors are getting printed

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?

Argument error in ActiveAdmin after change in devise sessions#new form

I am using Rails 4.0.4 and Ruby 2.1.1.
I made few changes in my devise login form after generating migration for username and find the ActiveAdmin is throwing following error.
Showing /Users/MyCom/.rvm/gems/ruby-2.1.1/bundler/gems/active_admin-3136ccb910e8/app/views/active_admin/devise/sessions/new.html.erb where line #8 raised:
wrong number of arguments (6 for 4..5)
Extracted source (around line #8):
<%= active_admin_form_for(resource, :as => resource_name, :url => send(:"#{scope}_session_path"), :html => { :id => "session_new" }) do |f|
f.inputs do
resource.class.authentication_keys.each { |key|
f.input key, :label => t('active_admin.devise.'+key.to_s+'.title'), :input_html => {:autofocus => true}
}
f.input :password, :label => t('active_admin.devise.password.title')
f.input :remember_me, :label => t('active_admin.devise.login.remember_me'), :as => :boolean if devise_mapping.rememberable?
Following is my code in views/devise/sessions/new
<div class="panel-body">
<div class="col-md-6">
<%= simple_form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f| %>
<div class="form-group">
<%= f.label :username %>
<%= f.input_field :username, class: "form-control", :autofocus => true %>
</div>
<div class="form-group">
<%= f.label :password %>
<%= f.password_field :password, class: "form-control" %>
</div>
<div class="form-group">
<div class="checkbox">
<%= f.check_box :remember_me %>
<%= f.label :remember_me %>
</div>
</div>
<div class="form-group">
<%= f.submit "Sign in", class: "btn btn-primary" %>
</div>
<% end %>
</div>
</div>
I was able to fix doing the following.
I had to change my config/initializers/simple_form_bootstrap.rb file.
I had added following which I had to take it out.
inputs = %w[
CollectionSelectInput
DateTimeInput
FileInput
GroupedCollectionSelectInput
NumericInput
PasswordInput
RangeInput
StringInput
TextInput
]
inputs.each do |input_type|
superclass = "SimpleForm::Inputs::#{input_type}".constantize
new_class = Class.new(superclass) do
def input_html_classes
super.push('form-control')
end
end
Object.const_set(input_type, new_class)
end
This issue is discussed in details here.
https://github.com/gregbell/active_admin/issues/2703