getting checkbox value in ruby on rails - ruby-on-rails

I have a checkbox below in a view page:
<table>
<tr>
<td>
<% #user_profession.each do |p| %>
<% if !p.Designation.blank? and p.Private? == "1" %>
<%= check_box(:ChkBx_Profession, {:id => "ChkBx_Profession",:value => "Profession"},true) %>
<%= label(:lb_Profession, "Profession") %>
<% else %>
<%= check_box(:ChkBx_Profession,{:id => "ChkBx_Profession",:value => "Profession"}) %>
<%= label(:lb_Profession, "Profession") %>
<% end %>
<% end %>
</td>
</tr>
</table>
Below is my controller page
if params[:ChkBx_Profession] == "1"
#blah = params[:ChkBx_Profession]
#publicprofession = params[:ChkBx_Profession]
Profession.delete_all(:UserID => current_user.id)
if !params[:tf_designation].blank?
#desig = params[:tf_designation]
#comp = params[:tf_company]
#fromdesigcom = params[:tf_fromdesignation]
#todesigcom = params[:tf_todesignation]
#public_profession = #publicprofession
#Profession = Profession.new( :UserID => current_user.id, :Designation => #desig, :Company => #comp, :Job_From => #fromdesigcom, :Job_To => #todesigcom, :Private? => #publicprofession )
#Profession.save
end
end
and I want to get the checkbox value means if checkbox is checked it gets me 1 and if checkbox is unchecked it gets me 0 but its get like this {"{:id=>\"ChkBx_Profession\", :value=>\"Profession\"}"=>"1"}. Kindly help me waiting for your reply.
Thanks

The second attribute on an check_box is the :value attribute. Try putting empty double quotes between the chec_box name AND the options:
<%= check_box(:YourCheckName, "",{Your Options}) %>

Related

Multiple saves with one submit

I need a form that includes 1 radio button, 1 submit button and a checkbox for each listed item.
Upon submit, the form should save a separate record for each checked item. Each saved item should include the value of the radio button along with other hidden values.
The form renders but crashes upon submit. The error message is:
undefined method `permit' for #<Array:0x007fb4b3b1a520>
My code is:
<%= form_tag(controller: "handoffs", action: "create", method: "post") %>
<%= radio_button_tag(:attend, "arrive") %>
<%= label(:handoff_arrive, "drop-off") %>
<%= radio_button_tag(:attend, "depart") %>
<%= label(:handoff_depart, "pick-up") %>
<% #parent.children.each do |child| %>
<%= check_box_tag "handoff[][check]" %>
<strong>
<%= child.fname %>
<%= child.mname %>
<%= child.lname %>
</strong><br>
<% group = Group.find(child.group_id) %>
<%= hidden_field_tag "handoff[][attend]" %>
<%= hidden_field_tag "handoff[][group_name]", :value => group.name %>
<%= hidden_field_tag "handoff[][child_id]", :value => child.id %>
<%= hidden_field_tag "handoff[][center_id]", :value => #center.id %>
<%= hidden_field_tag "handoff[][escort_fname]", :value => #parent.fname %>
<%= hidden_field_tag "handoff[][escort_lname]", :value => #parent.lname %>
<%= hidden_field_tag "handoff[][child_fname]", :value => child.fname %>
<%= hidden_field_tag "handoff[][child_mname]", :value => child.mname %>
<%= hidden_field_tag "handoff[][child_lname]", :value => child.lname %>
<% end %>
<%= button_to :submit, :class => 'f_submit' %>
<% end %>
Controller actions:
def new
#handoff = Handoff.new
#parent = current_parent
#center = Center.find(#parent.center_id)
end
def create
params["handoff"].each do |handoff|
if params[:handoff["check"]] != ""
#handoff = Handoff.new(handoff_params)
#handoff.save
end
end
end
def handoff_params
params.require(:handoff).permit(:attend, :group_name, :child_id, :center_id, :escort_fname, :escort_lname, :child_fname, :child_mname, :child_lname)
end
Request parameters (in error report)
{"utf8"=>"✓",
"authenticity_token"=>"snqrS130bXNV4bmMHOMlXeyhX2rWFVpmY/PYIv0jn97MBOLSWWw2jBbeYGPyjt7O9l5pRVNuFiu1qOwkGpELTA==",
"attend"=>"depart", "handoff"=>[{"check"=>"1", "attend"=>"",
"group_name"=>"{:value=>\"Gifted\"}", "child_id"=>"{:value=>60}",
"center_id"=>"{:value=>4}", "escort_fname"=>"{:value=>\"Richard\"}",
"escort_lname"=>"{:value=>\"Messing\"}",
"child_fname"=>"{:value=>\"Aaron\"}",
"child_mname"=>"{:value=>\"Lawrence\"}",
"child_lname"=>"{:value=>\"Schwartz\"}"}, {"check"=>"1", "attend"=>"",
"group_name"=>"{:value=>\"Arts & Crafts\"}",
"child_id"=>"{:value=>61}", "center_id"=>"{:value=>4}",
"escort_fname"=>"{:value=>\"Richard\"}",
"escort_lname"=>"{:value=>\"Messing\"}",
"child_fname"=>"{:value=>\"Joseph\"}",
"child_mname"=>"{:value=>\"Michael\"}",
"child_lname"=>"{:value=>\"Messing\"}"}], "method"=>"post",
"controller"=>"handoffs", "action"=>"create"}
I had similar case. First you need to create array with all values that you would like to export I used helper to do that. I'll show you my example:
def get_table_of_keywords(keywords)
exact_keywords = []
keyword_array.each do |key|
if !key.blank?
exact_keywords << {keyword: key, created_at: DateTime.now.in_time_zone, updated_at: DateTime.now.in_time_zone }
end
end
exact_keywords
end
And the you are using create:
#inserted_keywords = #campaign.keywords.create(get_table_of_keywords(params[:keyword][:keyword])) # add new keywords to the list

undefined method for nil:NilClass while using where method with condition

Here's a snippet of a code that is throwing an error:
<% count = 1 %>
<% exp = Expensestitle.where("expense_title_type_id = ?", 1) %>
<%= f.fields_for :aktiyary_items do |builder| %>
<tr>
<td style="width:5%;">
<label><%= exp[count].name %></label>
<%= builder.hidden_field :expensestitle_id, :class => 'form-control', :value => exp[count].id %>
</td>
<td style="width:1%">
<%= builder.number_field :initial_amount, :class => 'form-control inputs', :value => 0.0, :autocomplete => 'off', :precision => 2, :step => 'any' %>
</td>
</tr>
<% count += 1 %>
<% end %>
I'm trying to display all the 'names' from a table (expensestitle) whose expense_title_type_id = 1.
What I get is the following error:
undefined method `name' for nil:NilClass
But if I replace the second line of code from above with:
<% exp = Expensestitle.all %>
it displays all the 'name' from expense_title_type_id of 1 and 2. I just want to limit the name to an id of 1.
Any help would be appreciated.
Thanks

Cant get the Edit function Working

I have two models Employee and Overtime Definition The Associations are set like this
Employee
class Employee < ActiveRecord::Base
has_many :overtime_definitions
Overtime Definition
class OvertimeDefinition < ActiveRecord::Base
belongs_to :employee
I created an Overtime definition for an employee and it all looks fine.However I'm having trouble with editing the same for an employee.
overtime_definitions__controller:
def new
#flag = params[:flag]
#employee = Employee.find(params[:id])
#overtime = OvertimeDefinition.new
end
def create
#employee = Employee.find(params[:overtime_definition][:employee_id])
#overtime = OvertimeDefinition.new(params[:overtime_definition])
if (params[:half_day_extra_duty_hours][:hour].to_s !="" || params[:half_day_extra_duty_hours][:minute].to_s !="")
#overtime.half_day_extra_duty_hours = params[:half_day_extra_duty_hours][:hour].to_s + ":" + params[:half_day_extra_duty_hours][:minute].to_s + ":" + "00"
else
#overtime.half_day_extra_duty_hours = nil
end
if (params[:full_day_extra_duty_hours][:hour].to_s !="" || params[:full_day_extra_duty_hours][:minute].to_s !="")
#overtime.full_day_extra_duty_hours = params[:full_day_extra_duty_hours][:hour].to_s + ":" + params[:full_day_extra_duty_hours][:minute].to_s + ":" + "00"
else
#overtime.full_day_extra_duty_hours = nil
end
if #overtime.save
flash[:notice] = "Overtime Successfully Created for #{#employee.name}"
redirect_to :action => 'search_overtime'
end
end
def edit
#flag = params[:flag]
#overtime = OvertimeDefinition.find(params[:id][:employee_id])
#employee = Employee.find(params[:id])
end
def update
#employee = Employee.find(params[:id])
#overtime = OvertimeDefinition.find(params[:id])
if #overtime.update_attributes(params[:overtime_definition])
flash[:notice] = "Overtime Successfully Updated for #{#employee.name}"
redirect_to :action => 'search_overtime'
else
render :action => 'edit',:flag=>params[:flag]
end
end
Tried with these in the edit method
#overtime = OvertimeDefinition.find(params[:id][:employee_id])
#gives me can't convert Symbol into Integer error.
#overtime = OvertimeDefinition.find(params[:id])
#gives me Couldn't find OvertimeDefinition with ID=1353 error.Actually 1353 is the id of that employee.
3.#overtime = OvertimeDefinition.find(params[:employee_id])
#gives me couldn't find OvertimeDefinition without an ID error.
My _search_overtime_employee_list having these links for new and edit actions
<%=link_to "Calculation" ,:action => "new",:id=>employee.id, :flag=>"Calculation" %>
<%= link_to "Re-Calculate",:action => "edit",:id=>employee.id,:flag=>"Re-Calculate" %>
new.rhtml
<%= form_tag :action => 'create' do %>
<%= render :partial =>'form'%>
<center>
<%= submit_tag "Save",:onclick=>"return validate()",:class=>"buttons"%>
</center>
<% end %>
<%= link_to "Back" ,:action => "search_overtime" %>
edit.rhtml
<%= form_tag :action => 'update', :id=>#employee.id,:flag=> params[:flag],:value=>params[:id] %>
<%= render :partial =>'form'%>
<center>
<%= submit_tag "Update",:onclick=>"return validate()",:class=>"buttons"%>
</center>
<%= link_to "Back" ,:action => "search_overtime" %>
_form.rhtml
Employee Details
<table cellspacing="5">
<tr>
<td><b>Employee Code</b></td>
<%= hidden_field 'overtime_definition','employee_id',:value=>params[:id] %>
<td><%= #employee.employeeid %></td>
<td><b>Employee Name</b></td>
<td><%= #employee.personnel.display_full_name %></td>
</tr>
<tr>
<td><b>Department</b></td>
<td><%= #employee.department ? #employee.department.name : "" %></td>
<td><b>Designation</b></td>
<td><%= #employee.designation ? #employee.designation.name : "" %></td>
<td><b>Location</b></td>
<td><%= #employee.location.name%></td>
</tr>
</table>
</br>
<fieldset>
<table cellspacing="5">
<%= form_for :overtime_definition, :builder => LabelFormBuilder do |od| %>
<tr>
<td>
<label for="half_day_extra_duty_hours">
Half Day Extra Duty Hours
</label>
</td>
<td class ="datefamily">
<%= select_time(#overtime.half_day_extra_duty_hours, {:include_blank => true, :time_separator => ":",:prefix => "half_day_extra_duty_hours"})%>
</td>
</tr>
<tr>
<td>
<label for="full_day_extra_duty_hours">
Full Day Extra Duty Hours
</label>
</td>
<td class ="datefamily">
<%= select_time(#overtime.full_day_extra_duty_hours, {:include_blank => true, :time_separator => ":",:prefix => "full_day_extra_duty_hours"})%>
</td>
</tr>
<tr>
<%= od.sr_check_box :is_salary_basis, {}, true, false, :label => "Is Salary Basis"%>
</tr>
<tr>
<%= od.sr_check_box :is_fixed_amount, {}, true, false, :label => "Is Fixed Amount"%>
<td colspan="2" id="ov_hm" style="display: none">
Half Day Amount
<%= od.text_field :half_day_amount, :onkeypress => "return numbersonly(event)", :style => "width:40px" %>
</td>
<td colspan="2" id="ov_fm" style="display: none">
Full Day Amount
<%= od.text_field :full_day_amount, :onkeypress => "return numbersonly(event)", :style => "width:40px" %>
</td>
</tr>
<%end%>
</table>
I just lost out here completely in getting that edit action work.Any help is greatly appreciated!
Your current edit link is:
<%= link_to "Re-Calculate",:action => "edit",:id=>employee.id,:flag=>"Re-Calculate" %>
In your edit action:
#overtime = OvertimeDefinition.find(params[:id][:employee_id]) ## gives me can't convert Symbol into Integer error.
As per the edit link, you are directly passing :id in query params which you can access as params[:id]. There is no params[:id][:employee_id] in your params hash so when you say params[:id][:employee_id] Ruby tries to convert :employee_id to an integer which is a symbol. Hence, the error.
I think you should be passing id of OvertimeDefinition record in :id from your link. And access it as
#overtime = OvertimeDefinition.find(params[:id])
in the Controller's action.
#overtime = OvertimeDefinition.find(params[:id]) ## gives me Couldn't
find OvertimeDefinition with ID=1353 error.Actually 1353 is the id of
that employee.
This is because you are passing employee id in params[:id] so obviously this will not work. You need to pass OvertimeDefinition id here.
#overtime = OvertimeDefinition.find(params[:employee_id]) ## gives me
couldn't find OvertimeDefinition without an ID error.
You are not passing any :employee_id in query params within edit link. So, params[:employee_id] will be nil and find method fails because you didn't pass any id to it.
Solution :
Update your edit link as below:
<%= link_to "Re-Calculate",:action => "edit",:id=> #overtimedefinition.id , :employee_id => employee.id,:flag=>"Re-Calculate" %>
Replace #overtimedefinition.id with appropriate id of OvertimeDefinition record. As you have not shared the code, I don't know the name of OvertimeDefinition variable.
Update your edit action as:
def edit
#flag = params[:flag]
#overtime = OvertimeDefinition.find(params[:id])
#employee = Employee.find(params[:employee_id])
end

checkbox_tag check from comparing to database

In my users table, I have a column SkillType that has values "1", "2" and "3".
I want to check checkbox_tag in my view file when SkillType == "1" and I am trying the below given code:
def new
#user_basic=User.find(params[:id])
##user_education=Education.where(:UserID => params[:id])
end
And below given is my view file contents:
<td width="25%" align="left" style="vertical-align: bottom; color: #212121;" class="style6">
<%= check_box_tag :SkillType, "active", 1, true %>
<%= f.label(:SkillType, " Students") %>
</td>
But it is not checking the checkbox_tag.
You can check your checkbox in view label by this--
<%if #user_basic.SkillType == "1" %>
<%= check_box_tag :#user_basic.SkillType, :checked => true %>
<%end%>
In View
<%= check_box_tag :skill_type, :checked => get_status( #user_basic.SkillType) %>
In application_helper.rb
def get_status(skill_type)
skill_type.eql?("1") ? true : false
end
In view:
<% unless #user_basic.blank? %>
<% if #user_basic.SkillType.to_i == 1 %>
<%= check_box_tag 'Skilltype', #user_basic.id, 1, true %>
<% end %>
<% end %>
Hope that works !!

how to create an array in a helper and then loop through in a view

I have a poll, and I've created a helper to return a JSON object of all the results which works like so:
module PollVotesHelper
def poll_results_json(poll)
#poll_results = Array.new
#poll_results << {
:total_votes => poll.poll_votes.length,
:options => poll.poll_options.collect { |poll_option|
{
:id => poll_option.id,
:title => poll_option.title,
:vote_percentage => '33%',
:vote_count => poll_option.poll_votes.length
}
}
}
#poll_results.to_json
end
end
Then in the view I want to call it and loop through the options and output the title, etc...
<% poll_results_json(#poll)['options'].each do |poll_option| %>
<%= poll_option['id'] %>
<%= poll_option['title'] %>
<%= poll_option['vote_percentage'] %>
<%= poll_option['vote_count'] %>
<% end %>
The view is erroring. What's the right way to loop through the resulting JSON object?
Thanks
Your problem is, you want to iterate through JSON data, not a Ruby array. This is because to_json just returns a Ruby string with valid JSON inside. So instead of converting your whole Poll objects into JSON, you should just return the values as JSON:
<% #poll.poll_options.each do |poll_option| %>
<%= poll_option.id.to_json %>
<%= poll_option.title.to_json %>
<%= '33%'.to_json %>
<%= poll_option.poll_votes.length.to_json %>
<% end %>
I don't know why your are pushing Hash into an Array(#poll_results).Instead try something like
module PollVotesHelper
def poll_results_json(poll)
#poll_results = {
:total_votes => poll.poll_votes.length,
:options => poll.poll_options.collect { |poll_option|
{
:id => poll_option.id,
:title => poll_option.title,
:vote_percentage => '33%',
:vote_count => poll_option.poll_votes.length
}
}
}
#poll_results.to_json
end
end
The value returned from the method will be a string.first you need to parse json to process it.
in your view try like
<% JSON.parse(poll_results_json(#poll))['options'].each do |poll_option| %>
<%= poll_option['id'] %>
<%= poll_option['title'] %>
<%= poll_option['vote_percentage'] %>
<%= poll_option['vote_count'] %>
<% end %>

Resources