div class wrapping fieldwitherrors won't work - ruby-on-rails

My Rails application just wont add any class to fields with errors. Cant find wihat is the problem.
Got this in model:
validates_presence_of :name
validates_uniqueness_of :name
validates_presence_of :phone
Any ideas where to start looking for solutions ?
This is the view erb file which does not generate the required styled class:
<%= form_for :company, :url => {:action => 'create_lead'}, :html => {:class => "form-horizontal"} do |f| %>
<div class="">
<div class="span2">
<%= f.label :csdd_nr, "CSDD numurs" %>
<%= f.text_field :csdd_nr, {:class => "input-small"} %>
</div>
<div class="span4">
<%= f.label :name, "Nosaukums" %>
<%= f.text_field :name %>
</div>
<div class="span6">
<%= f.label :ap_veh_count, "Auto skaits" %>
<%= f.text_field :ap_veh_count, {:class => "input-small"} %><br /><br />
</div>
<div class="span6">
<%= f.label :office_adress_street, "Faktiskā adrese" %>
<%= f.text_field(:office_adress_street, {:placeholder => 'Iela', :class => "input-medium"}) %> <%= f.text_field(:office_adress_city, {:placeholder => 'Pilsēta', :class => "input-small"}) %> <%= f.text_field(:office_adress_postcode, {:placeholder => 'Pasta indekss', :class => "input-small"}) %>
</div>
<div class="span4">
<%= f.label :web, "Mājaslapa" %>
<%= f.text_field :web %><br /><br />
</div>
<div class="span4">
<%= f.label :phone, "Telefona numurs" %>
<%= f.text_field :phone %>
</div>
<div class="span4">
<%= f.label :email, "E-pasts" %>
<%= f.text_field :email %>
</div>
<div class="span4">
<%= f.label :company_field, "Uzņēmuma nodarbošanās" %>
<%= f.text_field :company_field %><br /><br />
</div>
<%= f.hidden_field(:company_status, :value => "3") %>
<div class="span12">
<br /><br />
<%= submit_tag("Saglabāt", :class => 'btn btn-primary') %>
<%= link_to "Atcelt", {:action => 'list_leads'}, :class => 'btn' %>
</div> def new_lead
#company = Company.new
end
def create_lead
#company = Company.new(params[:company])
if #company.save
flash[:success] = "Uzņēmums saglabāts"
redirect_to(:action => 'new_lead')
else
flash[:alert] = "!!! Uzņēmums nav saglabāts"
redirect_to(:action => 'new_lead')
end
end
</div>
<% end %>
OK, and here is the controller which saves the data to database:
def new_lead
#company = Company.new
end
def create_lead
#company = Company.new(params[:company])
if #company.save
flash[:success] = "Uzņēmums saglabāts"
redirect_to(:action => 'new_lead')
else
flash[:alert] = "!!! Uzņēmums nav saglabāts"
redirect_to(:action => 'new_lead')
end
end

This happens because you're redirecting instead of rendering, when there is a validation error. Your controller should look like:
def create_lead
#company = Company.new(params[:company])
if #company.save
flash[:success] = "Uzņēmums saglabāts"
redirect_to(:action => 'new_lead')
else
flash[:alert] = "!!! Uzņēmums nav saglabāts"
render(:action => 'new_lead')
end
end

Related

Rails 5: param is missing or the value is empty: verbalquestions

Been working at this for hours with no solution. Whenenever I load the resource of a new verbalquestion, and I fill out the form and hit submit, i get an error of: ActionController::ParameterMissing at /verbalquestions
param is missing or the value is empty: verbalquestions
verbalquestions_controller.rb
class VerbalquestionsController < ApplicationController
before_action :authenticate_user!
def index
#verbalquestions = Verbalquestion.all
if params[:tag]
#verbalquestions = Verbalquestion.tagged_with(params[:tag])
else
#verbalquestions = Verbalquestion.all
end
end
def new
#title = "Add a new VQ"
end
def show
#verbalquestion = Verbalquestion.friendly.find(params[:id])
end
def create
#verbalquestion = Verbalquestion.new(verbalquestion_params)
#verbalquestion.user = current_user
end
end
private
def verbalquestion_params
params.require(:verbalquestions).
permit(
:vq_title,
:vq_text,
:tag_list
)
end
verbalquestions/new.html.erb
<%= form_with scope: :verbalquestion, url: verbalquestions_path do |f| %>
<div class='field'>
<%= f.label :tag_list, 'Tags (separated by commas)' %><br/>
<%= f.text_field :tag_list %>
</div>
<div class="field">
<%= f.label "Verbal Question Title", :class=>'label' %>
<div class="control">
<%= f.text_field :vq_title, :id => 'vq_title', :class => 'textarea' %>
</div>
</div>
<div class="field">
<%= f.label "Verbal Question Test", :class=>'label' %>
<div class="control">
<%= f.text_area :vq_text, :id => 'vq_text', :class => 'textarea' %>
</div>
</div>
<p>
<%= f.submit %>
</p>
<% end %>
What am i doing wrong?
This is because your controller requires 'verbalquestions' in params
params.require(:verbalquestions)
You can try form_for #verbalquestion in your view and #verbalquestion = Verbalquestion.new() in controller>new.
Also, params.require(:verbalquestions) should be in a singular form like params.require(:verbalquestion).

Can't save nested attributes in rails 5

I have two model:
1.Personne
class Personne < ApplicationRecord
has_one :proprietaire
accepts_nested_attributes_for :proprietaire
validates :nom, :prenom, :tel, :email,
presence: true
end
2 Proprietaire
class Proprietaire < ApplicationRecord
belongs_to :personne
validates :commune_id, :quartier,
presence: true
end
the Controller is:
class PersonneController < ApplicationController
def display_proprietaires
#proprietaires = Personne.all
##proprietaires = #proprietaires.proprietaire
end
def new_proprietaire
#provinces = Province.where(:parentId => nil)
#communes = Province.where.not(:parentId => nil)
#personne = Personne.new
#personne.build_proprietaire
end
def create_proprietaire
#proprietaire = Personne.new(proprietaire_params)
#proprietaire.build_proprietaire
respond_to do |format|
if #proprietaire.save
flash[:notice] = "succes"
flash[:type] = "success"
format.html { redirect_to action: :display_proprietaires }
else
flash[:notice] = "fail"
flash[:type] = "warning"
format.html { redirect_to action: :display_proprietaires }
end
end
end
def proprietaire_params
params.require(:personne).permit(:nom, :prenom, :tel, :email, proprietaire_attributes: [:id, :commune_id, :quartier]).except(:province, :commit)
end
end
the View is:
<%= form_for #personne, :url => url_for(:controller=>'personne', :action=>'create_proprietaire' ) do |f| %>
<div class="row">
<div class="col-xs-6 col-sm-6 col-lg-6">
<div class="form-group">
<%= f.label(:nom, 'Nom : ') %>
<%= f.text_field :nom, {class: "form-control", placeholder: 'Nom'} %>
</div>
<div class="form-group">
<%= f.label(:prenom, 'Prenom : ')%>
<%= f.text_field :prenom, {class: "form-control", placeholder: "Prenom"} %>
</div>
<div class="form-group">
<%= f.label(:tel, 'Telephone : ')%>
<%= f.text_field :tel, {class: "form-control", placeholder: "Telephone"} %>
</div>
<div class="form-group">
<%= f.label(:email, 'Email : ') %>
<%= f.text_field :email, {class: "form-control", placeholder: "Email"} %>
</div>
<div class="form-group">
<%= label_tag(:province, 'Province : ') %>
<%= select_tag(:province, options_for_select(#provinces.collect{|value| [value.denomination, value.id]}), {class: "form-control", id: "province", remote: true} ) %>
</div>
<%= f.fields_for :proprietaire do |proprio| %>
<div class="form-group">
<%= proprio.label(:commune_id, 'Commune : ') %>
<%= proprio.select :commune_id, options_for_select(#communes.collect{|value| [value.denomination, value.id]}),{}, {class: "form-control", id: "commune"} %>
</div>
<div class="form-group">
<%= proprio.label :quartier, "Quartier" %>
<%= proprio.text_field :quartier, {class: "form-control", placeholder: "Quartier"} %>
</div>
<% end %>
<%= f.submit "Enregistre", {class: 'btn btn-info'} %>
<% end %>
Routes:
resources :personne do
collection do
post :create_proprietaire
get :display_proprietaires
get :new_proprietaire
end
end
I'm new in RoR, When I try to save nothing happens, I'm getting this:
Could someone helps me on this. Thank you!
You have your association set to required but it's missing.
Associations are set to required by default in rails 5 so if you want to keep one empty you need to set optional:true on your association in model

Form Error: First argument in form cannot contain nil or be empty

I'm following this tutorial to set up Devise integration with Stripe: http://www.jaredrader.com/blog/2013/12/18/a-stripe-integration
I have successfully setup Stripe as detailed and created the various controllers, models and views.
However, the forms are creating an ArgumentError in Users::Registrations#new
Here's the error code:
ArgumentError in Users::Registrations#new
Showing /home/action/workspace/mediadb/app/views/devise/registrations/new.html.erb where line #62 raised:
First argument in form cannot contain nil or be empty
The form:
<div class="panel panel-default">
<div class="panel-heading">
<% if params[:plan] == "2" %>
<h1>Sign up with premium!</h1>
</div>
<div class="panel-body">
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<%= hidden_field_tag 'plan', params[:plan] %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, autofocus: true, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :email %>
<%= f.email_field :email, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :password %>
<%= f.password_field :password, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation, class: "form-control" %>
</div>
<h2>Payment</h2>
<%= f.hidden_field :stripe_card_token %>
<div class="form-group">
<%= label_tag :card_number, "Credit Card Number" %>
<%= text_field_tag :card_number, nil, name: nil, class: "form-control" %>
</div>
<div class="form-group">
<%= label_tag :card_code, "Security Code on Card (CVV)" %>
<%= text_field_tag :card_code, nil, name: nil, class: "form-control" %>
</div>
<div class="form-group">
<%= label_tag :card_month, "Card Expiration" %>
<%= select_month nil, {add_month_numbers: true}, {name: nil, id: "card_month"}%>
<%= select_year nil, {start_year: Date.today.year, end_year: Date.today.year+15}, {name: nil, id: "card_year"}%>
</div>
<div id="stripe_error">
<noscript>JavaScript is not enabled and is required for this form. First enable it in your web browser settings.</noscript>
</div>
<div class="form-group">
<%= f.submit "Sign up", class: "btn btn-lg btn-success" %>
</div>
<% end %>
</div>
<% else %>
<h1>Sign up for free</h1>
</div>
<div class="panel-body">
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), html: { id: "free_plan"}) do |f| %>
<%= devise_error_messages! %>
<%= hidden_field_tag 'plan', params[:plan] %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, autofocus: true, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :email %>
<%= f.email_field :email, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :password %>
<%= f.password_field :password, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation, class: "form-control" %>
</div>
<div class="form-group">
<%= f.submit "Sign up", class: "btn btn-lg btn-primary" %>
</div>
<% end %>
<% end %>
</div>
</div>
The routes.rb file:
Rails.application.routes.draw do
resources :lists
resources :publications
resources :contacts
devise_for :users, controllers: { registrations: 'users/registrations' }
devise_scope :user do
get '/sign_up', to: 'users/registrations#new', as: :sign_up
get '/sign_in', to: 'devise/sessions#new', as: :sign_in
get '/:id/edit', to: 'users/registrations#edit', as: :edit
put 'users/update_plan', :to => 'users/registrations#update_plan'
put 'users/cancel_plan', :to => 'users/registrations#cancel_plan'
end
resources :users, only: [:index, :show]
# root should always be last
root to: 'pages#home'
end
The Registration controller:
class Users::RegistrationsController < Devise::RegistrationsController
def new
unless (params[:plan] == '1' || params[:plan] == '2')
flash[:notice] = "Please select a plan to sign up."
redirect_to root_url
end
end
def update_plan
#user = current_user
#user.update_attributes(plan_id: params[:plan], email: params[:email], stripe_card_token: params[:user][:stripe_card_token])
if #user.plan_id == 2
#user.save_with_payment
redirect_to edit_user_registration_path, notice: "Updated to premium!"
else
flash[:error] = "Unable to update plan."
render :edit
end
end
def cancel_plan
#user = current_user
if #user.cancel_user_plan(params[:customer])
#user.update_attributes(stripe_customer_token: nil, plan_id: 1)
flash[:notice] = "Canceled subscription."
redirect_to edit_user_registration_path
else
flash[:error] = "There was an error canceling your subscription. Please notify us."
render :edit
end
end
private
def build_resource(*args)
super
if params[:plan]
resource.plan_id = params[:plan]
if resource.plan_id == 2
resource.save_with_payment
else
resource.save
end
end
end
def setup
plans = Plan.all
plans.each do |plan|
unless plan.id == 1
#startup_plan = plan
end
end
end
end
Any idea what's wrong?
Update Users::RegistrationsController#new as follows
def new
if (params[:plan] == '1' || params[:plan] == '2')
super
else
flash[:notice] = "Please select a plan to sign up."
redirect_to root_url
end
end

How to writer strong_params rails4

I am not getting exact solution for finding the strong params for given parameters.
Please help me on this
"service"=>{"1"=>{"client_id"=>"testid", "client_secret"=>"testsecret"}, "2"=>{"client_id"=>"testkey", "client_secret"=>""}, "3"=>{"client_id"=>"", "client_secret"=>""}}
I tried
def service_params
params.require(:service).permit(:id, :client_id, :client_secret)
end
I am getting error
Unpermitted parameters: 1, 2, 3
EDIT:
my form is
<%= form_for :service, :url => update_config_path, :html => { :class => "form-horizontal", :method => "put", :remote => true } do %>
<% #services.each do |s| %>
<%= fields_for "service[]", s do |service_field| %>
<fieldset>
<legend><%= s.name %></legend>
<div class="form-group">
<%= service_field.label :client_id, "Consumer Key", :class => "col-sm-2 control-label" %>
<div class="col-sm-10">
<%= service_field.text_field :client_id, :class => "form-control" %>
</div>
</div>
<div class="form-group">
<%= service_field.label :client_secret, "Consumer Secret", :class => "col-sm-2 control-label" %>
<div class="col-sm-10">
<%= service_field.text_field :client_secret, :class => "form-control" %>
</div>
</div>
</fieldset>
<% end %>
<% end %>
<%= submit_tag %>
<% end %>
I haven't tested it, but something like this might work:
def service_params
params.require(:service).map do |_, p|
p.permit(:id, :client_id, :client_secret)
end
end
Something like this could work:
def service_params
params.require(:service).permit.tap do |whitelisted|
whitelisted["1"] = params["1"]
whitelisted["2"] = params["2"]
whitelisted["3"] = params["3"]
end
end

Validation for create action causing routing error

Validation for the create action are not working, I have made validation for the field to be present, but if I keep the fields empty and press submit, I get routing error, if I fill in the complete fields, It works perfectly fine. Also, the validation works perfectly fine for the update action.
Here is the view:
<%= stylesheet_link_tag 'gmaps4rails' %>
<%= form_for #estate, :html => { :class => 'form-horizontal',:multipart => true } do |f| %>
<% if #estate.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#estate.errors.count, "error") %> prohibited this estate from being saved:</h2>
<ul>
<% #estate.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<script>
function enableDisable(bEnable, textBoxID)
{
document.getElementById(textBoxID).disabled = !bEnable
}
</script>
<div class="control-group">
<%= f.label :Name, "Property/Tenant Name", :class => 'control-label' %>
<div class="controls">
<%= f.text_field :Name, :class => 'text_field', :placeholder => "e.g., Saxbys Coffee" %>
</div>
</div>
<div class="control-group">
<%= f.label :Address, :class => 'control-label' %>
<div class="controls">
<%= f.text_area :Address, :class => 'text_area', :cols => '10', :rows => '10', :placeholder => "e.g., 1236 36th Street NW Washington, DC 20007" %>
</div>
</div>
<div class="control-group">
<%= f.label :asset, "Upload Picture", :class => 'control-label' %>
<div class="controls">
<%= f.file_field :asset %>
</div>
</div>
<% if #estate.asset.present? %>
<div class="control-group">
<%= f.label "Delete Existing Picture", :class => 'control-label' %>
<div class="controls">
<%= f.check_box(:delete_asset) %>
</div>
</div>
<% end %>
<!-- <div class="control-group">
<%= f.label :Mgmt, "Would you like to share this property with your Real Estate Management Company?", :class => 'control-label' %>
<div class="controls">
<input type="checkbox" id="chkbox" onchange="document.getElementById('txtBox').disabled=!this.checked;" checked="checked" />
</div>
</div> -->
<% if current_user.Company.nil? %>
<div id="flip"><a>Would you like to share this property with your Management Company?</a></div>
<br />
<div id="panel">
<div class="control-group">
<%= f.label :Mgmt, "Company Name", :class => 'control-label' %>
<div class="controls">
<%= f.text_field :Mgmt, :class => 'text_field', :id => 'txtBox'%>
</div>
</div>
<div class="control-group">
<%= f.label :companyemail, "Company Email", :class => 'control-label' %>
<div class="controls">
<%= f.text_field :companyemail, :class => 'text_field', :id => 'txtBox'%>
</div>
</div>
</div>
<% end %>
<div class="form-actions">
<% if current_page?(controller:"estates", action:"edit", :id => params[:id] || 0)%>
<%= f.submit "Update Property Details", :class => 'btn btn-info' %>
<% else %>
<%= f.submit "Upload Property Details", :class => 'btn btn-info' %>
<% end %>
<% end %>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("slow");
});
});
</script>
Here is the controller:
def create
# #estate = Estate.new(params[:estate])
if current_user.Company.nil?
#estate = current_user.estates.build(params[:estate])
else
serve = User.find(##key)
#estate = Estate.new(params[:estate])
#estate.user_id = serve.id
#estate.Mgmt = current_user.Company
end
respond_to do |format|
if #estate.save
if current_user.Company.nil?
if #estate.companyemail = ''
#
else
EstateMailer.company_confirmation(#estate).deliver
end
end
format.html { redirect_to #estate, notice: 'Property details were successfully updated.' }
format.json { render json: #estate, status: :created, location: #estate }
else
format.html { render action: "new" }
format.json { render json: #estate.errors, status: :unprocessable_entity }
end
end
end
Error message:
No route matches {:action=>"show", :controller=>"estates", :id=>#<Estate id: nil, Name: "", Address: "", created_at: nil, updated_at: nil, user_id: 5, asset_file_name: nil, asset_content_type: nil, asset_file_size: nil, asset_updated_at: nil, Mgmt: "", companyemail: "", latitude: nil, longitude: nil, gmaps: nil>}
routes.rb
resources :feedbacks
root to: 'home#index'
devise_for :users, path_names: {sign_in: "login", sign_out: "logout"},
controllers: {omniauth_callbacks: "omniauth_callbacks"}
resources :profiles
resources :estates do
resources :records do
resources :documents
end
end
get 'faq/faqs'
match '/records',to: 'estates#record'
get 'management/index'
match 'management/show', to: 'management#show'
match 'management/showrecord', to: 'management#showrecord'
after a little chat with Hrishikesh Sardar the bug was fixed, the problem was in if block of the create action:
if current_user.Company.nil?
#estate = current_user.estates.build(params[:estate])
else
serve = User.find(##key)
#estate = Estate.new(params[:estate])
#estate.user_id = serve.id
#estate.Mgmt = current_user.Company
end
this line:
#estate = current_user.estates.build(params[:estate])
had to be replaced by:
#estate = Estate.new(params[:estate])
#estate.user_id = current_user.id
somehow current_user.estates.new(params[:estate]) didn't worked, even if the relation between estate and user was built as required.

Resources