Don't show empty field in rails4 - ruby

<p>
<% if #person.name %>
<strong>Name:</strong>
<%= #person.name %>
<% end %>
</p>
<p>
<% if #person.gender %>
<strong>Gender:</strong>
<%= #person.gender %>
<% end %>
</p>
<p>
<% unless #person.age.blank? %>
<strong>Age:</strong>
<%= #person.age %>
<% end %>
</p>
<p>
<% unless #person.address.blank? %>
<strong>Address:</strong>
<%= #person.address %>
<% end %>
</p>
This code works fine. Its not showing empty field , but I want to know that is there any other way to do so. Because here I'm repeating same type of code again and again. Can I use any helper that stop showing empty fields?

There are many ways to do this, and the 'best' is dependent on your situation. As long as the labels are always the same as the attributes, one way you could do it is in a simple partial:
#person/_attribute.html.erb
<% if #person.public_send attribute != nil %>
<strong><%= attribute.to_s.capitalize %></strong>
<%= #person.public_send attribute %>
<% end %>
which would make your view look like this:
<p>
<%= render 'attribute' :attribute => :name %>
</p>
<p>
<%= render 'attribute' :attribute => :gender %>
</p>
<p>
<%= render 'attribute' :attribute => :age %>
</p>
<p>
<%= render 'attribute' :attribute => :address %>
</p>
I have to take this opportunity to preach HAML at you, though - your code could look like this!
#person/_attribute.haml
- if #person.public_send attribute != nil
%strong= attribute.to_s.capitalize
= #person.public_send attribute
#person/show.haml
%p= render 'attribute' :attribute => :name
%p= render 'attribute' :attribute => :gender
%p= render 'attribute' :attribute => :age
%p= render 'attribute' :attribute => :address

Related

How to solve ParameterMissing error using ROR

Please help me to solve the below error.
Error:
ActionController::ParameterMissing in CustmersController#create
param is missing or the value is empty: users
When i am submitting the data,this error is coming.
My code is as follows
views/custmers/new.html.erb
<h1>Enter your data here</h1>
<center>
<%= form_for #users,:url => {:action => 'create'} do |f| %>
<% if #users.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#users.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #users.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<label for="name">Name:</label>
<%= f.text_field :name,placeholder:"Enter your name",:class => "input-field" %>
</p>
<p>
<label for="email">Email:</label>
<%= f.email_field :email,placeholder:"Enter your email",:class => "input-field" %>
</p>
<p>
<label for="phone">Phone no:</label>
<%= f.telephone_field :phoneno,placeholder:"Enter your phone number",:class => "input-field" %>
</p>
<p>
<%= f.submit "Submit" %>
</p>
<% end %>
<%= link_to "BACK",custmers_index_path %>
</center>
controller/custmers_controller.rb
class CustmersController < ApplicationController
def index
end
def new
#users=Custmer.new
end
def show
end
def create
#users=Custmer.new(user_params)
if #users.save
flash[:notice]="You have signed up successpully"
flash[:color]="valid"
redirect_to :action => 'index'
else
flash[:alert]="You have not signed up successfully"
flash[:color]="invalid"
render :new
end
end
private
def user_params
params.require(:users).permit(:name,:email,:phoneno)
end
end
model/custmer.rb
class Custmer < ActiveRecord::Base
EMAIL_REGEX = /\A[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\z/i
validates :name,presence:true,length: { minimum: 5 }
validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
validates :phoneno, presence: true,length: {minimum: 10}
end
I am using rails version-4.2.0 and ruby version-1.9.3.Please help me to resolve this error.
If you look at the stack trace accompanying your error, you could tell definitely where the problem is -- look for the first line in the stack trace that refers to your code (and not library code).
But a fair guess is the require(:users) line in your controller. It looks like you either copy/pasted this code from another controller, or changed the name of your controller after generating it as part of your scaffold.
It should be requires(:custmer) instead, as that is the class of the thing you're submitting.
As a general approach, you should follow the standard Rails practices for naming things, throughout. If you really want to use the misspelled, Custmer class, have at it, but use #custmr inside your controller and views to refer to an instance, not #users.

Get value of a hidden field tag Ruby on Rails

I am lost, I do not know what I'm doing wrong! I have 4 radio buttons and a hidden field (value = "1"). When you click on the second radiobutton, the value of the hidden field changes to 2 and so on. This works fine with a js function.
Different divs will be showed when a different radiobutton is selected. Now, when I'm trying to get the value of the hidden field in my controller it always returns nil.
Here's the code:
view:
(radiobuttons, hiddenfield and one div)
<div>
<%= form_tag patients_path do %>
<%= radio_button_tag 'searchRBN', 'patient', true, :onchange => "checkRadioButton()" %>
<%= label_tag :byPatient_patient, "Patient" %>
<%= radio_button_tag 'searchRBN', 'staff', false, :onchange => "checkRadioButton()" %>
<%= label_tag :byStaff_staff, "Staff" %>
<%= radio_button_tag 'searchRBN', 'ocmw', false, :onchange => "checkRadioButton()" %>
<%= label_tag :byOcmw_ocmw, "OCMW" %>
<%= radio_button_tag 'searchRBN', 'mutuality', false, :onchange => "checkRadioButton()" %>
<%= label_tag :byMutuality_mutuality, "Mutuality" %>
<%= hidden_field_tag :hidden_one, "1" %>
<% end %>
</div>
<div id="searchByPatient">
<%= form_tag patients_path, :method => 'get' do %>
<p>
<%= text_field_tag :search1, params[:search1] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
</div>
controller:
def index
#staff_all = Staff.all
#ocmw_all = Ocmw.all
#mutuality_all = Mutuality.all
debugger
if params[:hidden_one] == '1'
#patients = Patient.searchByName(params[:search1])
elsif params[:hidden_one] == '2'
#patients = Patient.searchByStaff(params[:search2])
else
#patients = Patient.all
end
end
It's because you have two forms. When you submit the second form it won't send the fields of the first form. If you put everything in one form it will work as expected.
Use only single form:
Also as a workaround use two submit tag in a single form:
differentiate both the action with params[:action]
For Example:
<%= form_for :attachment_metadata, :url=>{:action=>'delete_files'}, :html=>{:onsubmit=> "return confirm('Are you sure, you want to delete selected files?');",:multipart => true} do |f| %>
<table>
..........Some stuff here..........
</table>
<%= submit_tag 'Reprocess', :class =>'button' %>
<%= submit_tag 'Remove', :class =>'button' %>
<% end %>
params[:commit] can differentiate the actions of two submit tags.
#action = params[:commit]
it gives #action value as "Reprocess" if your click the Reprocess button and gives "Remove" value if you click the Remove button,
Then you will get your values.

Rails submit remote form onclick of radio button

I have a form that submits when you chose a radio button (below). Currently the page refreshes when it submits and I'd like to use Jquery and remote submission so it doesn't refresh. Any idea where to start with this?
<%= simple_form_for(#order) do |f| %>
<%= f.input :orderstatus_id, :as => :radio, :label => false do %>
<% current_user.account.orderstatuses.order(:status_order).each do |os| %>
<p id="invoice-color-select">
<%= f.radio_button :orderstatus_id, os.id, :class => 'selector', :onclick => "this.form.submit();" %>
<%= f.label "#{os.name}", :style => "background: ##{os.color}", :class => 'status' %>
</p>
<% end %>
<% end %>
<div style="margin-top:20px">
<% if !current_user.account.has_plan? || current_user.account.plan_key== "ultra" %>
<a class="fancybox" href="#editstatus">Edit</a>
<% end %>
</div>
<% end %>
I added this into my view:
<%= f.radio_button :orderstatus_id, os.id, :class => 'selector', :onclick => "this.form.submit();" %>
You can see the :onclick portion here.

How to pass name of form_for's method to partial in rails?

Good day! Little newbee question:
let's say I want to generate fields of form_for helper of special appearance. Thus to not to repeat complex code to generate many fields of model, I render some partial and pass there parameters. There is a reference to form object amongst them. Question is what pass to render method to call in the partial necessary method of form object? For example I want to generate this time email_field:
<%= form_for #order do |f| %>
<%= render :partial => 'form_field_special', :locals => {:form => f, :type => :email_field, :labelcaption => "SpcName"} %>
<% end %>
and partial itself:
<div class="control-group">
<%= f.label :name, <%= labelcaption %> , :class => "control-label" %>
<div class="controls">
<%= f.type :name %> # ??????
</div>
</div>
thank you guys!
Use ruby power. Object#send method:
<%= form_for #order do |f| %>
<%= render :partial => 'form_field_special', :locals => {..., :field_type => 'email_field'} %>
<% end %>
<%= f.send(field_type, :name) %>
The following method proved as the fastest way to invoke ruby object's function by its name:
m = form.method(name_of_the_method)
m.call(parameters)

Rails 3.1 nested form issue

Ive got the following scenario:
cmsasset model that is container for image using paperclip to upload and store, location model that can have attached cmsassets in a habtm join table approach
location accepts nested attributes for cmsassets here's the exact model code:
accepts_nested_attributes_for :cmsassets, :allow_destroy => true
now when i try to use the following in my form code the nested form is not displayed:
<%= form_for #location do |f| %>
<%= render 'shared/error_messages', :target => #location %>
<p>Name<br />
<%= f.text_field :name %></p>
<p>Description<br />
<%= f.text_area :description %></p>
<p>Location Tags (Separated by a Comma)<br />
<%= f.text_field :tag_names %></p>
<%= render :partial => 'shared/contact_info_form', :locals => {:f => f} %>
<p>Splash Image:<br />
<%= f.fields_for :cmsassets do |cmsasset_form| %>
<%= cmsasset_form.number_field :client_id, :type => 'hidden', :value => session[:current_client] %>
<p>Image Name:<br />
<%= cmsasset_form.text_field :name %></p>
<p>Description:<br />
<%= cmsasset_form.text_field :description %></p>
<p><%= cmsasset_form.file_field :attachment %><br />
<%= cmsasset_form.text_field :cms_asset_type, :type => 'hidden', :value => 'Splash' %></p>
<% end %></p>
<p>Display Address:<br />
<%= f.text_field :display_addr %></p>
<p>Latitude<br />
<%= f.number_field :latitude %></p>
<p>Longitude<br />
<%= f.number_field :longitude %></p>
<p>Trigger Radius<br />
<%= f.number_field :trigger_radius%></p>
<p>Published >> <%= f.check_box :published %></p>
<p>Expiration Date<br />
<%= f.text_field :expiration_date %></p>
<br />
<%= f.submit "Save" %>
However, when I make cmsassets singular in the nested form call it renders but fails obviously because of the habtm data structure...
whats crazy is that this approach works using the nested_form gem, with the sole exception of paperclip causing a failure in this case because we use dynamic styles at the model level..
if anyone can shed some light on either of these issues i'd be very interested to hear some ideas!
It's not valid HTML to write nested forms.
Try to place the upload form outside the main form.

Resources