Set Rails date format for view - ruby-on-rails

What's the most efficient way to display a date in a view in dd/mm/yyyy format?
I modified config/initializers/date_time.rb as such:
# Date
Date::DATE_FORMATS[:default] = "%d/%m/%Y"
However, I have a dropdown list that contains dates, and I use that to pass a date parameter date_id for searching purpose. If I use the above line, it doesn't return any results when it should.
My code:
balances_controller.rb
def statement
#dates = Balance.select("distinct(date)").order('date desc')
if (params[:date_id].blank?)
#latestDate = Balance.order('date desc').first.date
else
#latestDate = params[:date_id]
end
#summaryBalances = Balance.joins(:account).order('accounts.credit').where('date = :abc', {abc: #latestDate})
end
statement.html.erb
<h1>Statement at <%= #latestDate %></h1>
<%= form_tag("/statement", method: "get") do %>
<%= select_tag "date_id", options_for_select( #dates.collect {|d| [ d.date, d.date ] }) %>
<%= submit_tag("Search") %>
<% end %>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Account</th>
<th>Balance</th>
<th colspan="1"></th>
</tr>
</thead>
<tbody>
<% #summaryBalances.each do |balance| %>
<tr>
<td><%= balance.account.name %></td>
<td class='account-balance'><%= number_to_currency(balance.balance, unit: "£") %></td>
<td><%= link_to 'Edit', edit_balance_path(balance) %></td>
</tr>
<% end %>
</tbody>
</table>
</div>
UPDATE:
html output:
<form action="/statement" accept-charset="UTF-8" method="get"><input name="utf8" type="hidden" value="✓" />
<select name="date_id" id="date_id"><option value="2015-11-30">30/11/2015</option>
<option value="2015-10-31">31/10/2015</option>
<option value="2015-09-30">30/09/2015</option></select>
<input type="submit" name="commit" value="Search" />
</form>
I'm not sure if this is the most efficient way of resolving this but I've managed to do what I need it to do by creating two separate helper methods. One to display the date in dd/mm/yyyy format and one to return the date in yyyy-mm-dd format for the parameter.
def date_format(date)
date.to_date.strftime("%d/%m/%Y")
end
def date_format2(date)
date.to_date.strftime("%Y-%m-%d")
end
Updated statement.html.erb
....
<%= form_tag("/statement", method: "get") do %>
<%= select_tag "date_id", options_for_select( #dates.collect {|d| [ date_format(d.date), date_format2(d.date) ] }) %>
<%= submit_tag("Search") %>
<% end %>
....

Related

how to set multiple default form values on submission in rails?

attendance table that takes has attribute status, date,recuritment_id, and project_site_id .
project_site has one_to_many association with attendance
recuritmenthas one_to_many association with attendance.
i am taking attribute from recruitment table when attribute status is joined in attendance#form view.
<% (1..(Time.days_in_month #project_site.attendance_month.strftime("%m").to_i)).each do |date| %>
here #project_site.attendance_month contains the attendance month value. based on month i calculate number of days column along with name from recuritmnet table.
here is view-
holydays master contains corresponding month holyday's date and in view it auto match date and prints "H",
All input default selected as P. there is final submission_button that chnages boolean attribute. now on final submission i want to push all default selected P into attendance table.
attendance_controller.rb
def new
if #project_site.submission_status == false
#attendance = Attendance.new
#date = HolydayCalendar.all
#recruitment = Recruitment.all.where(current_status: "2")
else
redirect_to project_site_attendances_path
end
end
from.html.erb (attendance controller view)
<table>
<thead>
<tr>
<th class="attendance-emp-name">Emp. Name</th>
<% (1..(Time.days_in_month #project_site.attendance_month.strftime("%m").to_i)).each do |date| %>
<th class="text-center"><%= date %></th>
<% end %>
</tr>
</thead>
<tbody>
<% #recruitment.where(location: #project_site.site_id).each do |recruitment| %>
<tr>
<td class="attendance-emp-name"><%= recruitment.name %></td>
<% (1..(Time.days_in_month #project_site.attendance_month.strftime("%m").to_i)).each do |date| %>
<%= form_with(model: attendance, :html => {:id => 'attendance-form-validation'}, url:[#project_site, #attendance], local: true) do |f| %>
<% if HolydayCalendar.find_by(date: (#project_site.attendance_month.strftime("%Y-%m")+"-"+date.to_s), total_site_id: #project_site.site_id)%>
<td class="holyday text-center"><%= "H" %></td>
<% elsif recruitment.attendances.find_by(attendance_date: (#project_site.attendance_month.strftime("%Y-%m")+"-"+date.to_s)) == nil %>
<td>
<%= f.select :status, [['P', 1], ['A', 2], ['L', 4], ['WE', 5], ['CO', 6]], {}, { onchange: 'this.form.submit()', class: 'attendance-select-input' } %>
</td>
<% else %>
<% attendance_value = recruitment.attendances.find_by(attendance_date: (#project_site.attendance_month.strftime("%Y-%m")+"-"+date.to_s)) %>
<%if attendance_value.status == 1 %>
<td class="presant text-center"><%="P" %></td>
<% elsif attendance_value.status == 2 %>
<td class="absent text-center"><%="A" %></td>
<%elsif attendance_value.status == 3 %>
<td class="holyday text-center"><%="H" %></td>
<%elsif attendance_value.status == 4 %>
<td class="leave text-center"><%= "L" %></td>
<%elsif attendance_value.status == 5 %>
<td class="weekend text-center"><%= "WE" %></td>
<%elsif attendance_value.status == 6 %>
<td class="compoff text-center"><%= "CO" %></td>
<% end %>
<% end %>
<%= f.hidden_field :attendance_date, value: (#project_site.attendance_month.strftime("%Y-%m")+"-"+date.to_s)%>
<%=f.hidden_field :recruitment_id, value: recruitment.id%>
<%=f.hidden_field :project_site_id, value: #project_site.id%>
<% end %>
<% end %>
</tr>
<% end %>
</tbody>
</table>
<% if #project_site.submission_status == true %>
<div class="text-center">
<%= link_to "Submit Attendance", set_submission_status_project_site_path(#project_site), method: :put, data: { confirm: 'Make Sure you marked all attendance before submission' }, :class=>"button primary disabled" %>
</div>
<% else %>
<div class="text-center">
<%= link_to "Submit Attendance", set_submission_status_project_site_path(#project_site), method: :put, data: { confirm: 'Make Sure you marked all attendance before submission' }, :class=>"button primary" %>
</div>
<% end %>
project_sites_controller.rb
def set_submission_status
#project_site = ProjectSite.find(params[:id])
#project_site.update(submission_status: true)
end
It's a little unclear what your question is, but I gather it has to do with your form sending back an array op options.
If you want your html form to return an array of information, then you need to indicate it in your html using the name = "attendance[]" syntax, notice the square brackets.
Check out this article on the subject https://mattstauffer.com/blog/a-little-trick-for-grouping-fields-in-an-html-form/

Ruby How do I get a 2d array from HTML form?

I am trying to write a tickets booking system.
I have a 2d array stored the seat and the status
#movie1 = [["A1", 0], ["A2", 0], ["A3", 1],["A4", 1], ["A5", 1], ["A6", 1], ["A7", 1], ["A8", 1], ["A9", 0], ["A10", 1]]
And this is the view
<form action= "seat/test4" method="get">
<table>
<% for i in 0..9 do %>
<% if i == 0 then %>
<tr>
<% end %>
<% if #movie1[i][1] == 1 then %>
<td bgcolor="red">
<%= #movie1[i][0] %>
<input type = button value = "X"
</td>
<% else %>
<td bgcolor="green">
<%= #movie1[i][0] %>
<input type="checkbox" id= <%= #movie1[i][0] %> name = <%= #movie1[i][0] %> >
</td>
<% end %>
<% if i == 9 then %>
</tr>
<% end %>
<% end %>
</table>
<input type="submit" value="Purchase">
</form>
How can I get the checkbox value and change the #movie1[i][1] = 1 ?
If you are trying to change #movie1. #movie1 is a ruby variable it renders when page loads and it cannot be changed after that. if you really want to change the variable without page reload you can do it via Ajax call Rails itself has feature to accomplish that.
To know more refer this link:
Working with javascript in Rails
Also Refer about rails partial
Rails Partial
This is used to create subtemplates, is usefull for dynamic cases like this.
As a Suggestion you can also implement the view as follows
<form action= "seat/test4" method="get">
<table>
<tr>
<% #movie1.each do |m| %>
<% if m[1] == 1 %>
<td bgcolor="red">
<%= m[0] %>
<input type = button value = "X" />
</td>
<% else %>
<td bgcolor="green">
<%= m[0] %>
<input type="checkbox" id= <%= m[0] %> value="<%= m[0] %>" name = <%= m[0] %> />
</td>
<% end %>
<% end %>
</tr>
</table>
<input type="submit" value="Purchase">
</form>
Also add value attribute to checkbox tag

Format Active Record Data before rendering as JSON

I have a data table that i am going to convert to Ajax and have to format the JSON values into the right formats.
In this example how would i format the tables.created_at time-stamp to MM/DD
format...
tables = Table.where(:state => "Missouri")
respond_to do |format|
format.json { render json: tables }
end
In the DOM i would do a loop through the data and do this where i needed it: Chronic.parse(s.created_at.to_date).strftime("%m/%d")
And as you can see i have alot of additional formatting to do to the data before it is returned as JSON:
<% if #load_search.nil? %>
<tr></tr>
<% else %>
<% #load_search.each do |s| %>
<tr id="row_<%= s.id %>">
<td align="center">
<%= s.id %>
</td>
<td class="count" align="center">
<%= s.results %>
</td>
<td align="center">
<%= Chronic.parse(s.created_at.to_date).strftime("%m/%d") %>
</td>
<td align="center">
<% if s.equipment.empty? %>
All Equipment
<% else %>
<%= s.equipment.pluck(:code).to_s.gsub("[","").gsub(']','').gsub('"','') %>
<% end %>
</td>
<td align="center">
<% if s.origin_id.nil? %>
<%= s.origin_states %>
<% else %>
<%= Location.find(s.origin_id).cs unless s.origin_id.nil? %>
<% end %>
</td>
<td align="center">
<%= s.origin_radius_cs %>
</td>
<td align="center">
<% if s.dest_id.nil? %>
<%= s.dest_states %>
<% else %>
<%= Location.find(s.dest_id).cs unless s.dest_id.nil? %>
<% end %>
</td>
<td align="center">
<%= s.dest_radius_cs %>
</td>
<td align="center">
<%= s.length.to_s + ' ft.' unless s.length.nil? %>
</td>
<td align="center">
<%= s.weight.to_s + ',000 lbs' unless s.weight.nil? %>
</td>
<td align="center">
<% if s.ltl %>
Partial
<% elsif s.both %>
Full
<% else %>
Both
<% end %>
</td>
<td align="center">
<%= Chronic.parse(s.pickup.to_date).strftime("%m/%d") %>
</td>
<td align="center">
<%= Chronic.parse(s.delivery.to_date).strftime("%m/%d") unless s.delivery.nil?%>
</td>
</tr>
<% end %>
<% end %>
You can override the ActiveRecord getter as
class Model
def created_at
self[:created_at].strftime("%m/%d")
end
end

advanced Search (checkboxes and selection)

I'm having a problem with my advanced search.
Essentially, its an advanced search for bands (name, style, bandpicture by checkboxes (checked: have a bandpicture))
Here is the code.
result.html.erb
<table >
<colgroup>
<col width="250" />
</colgroup>
<tr>
<td>
<label for="name">Filter</label></br>
<%= form_tag band_path do %>
<label for="Style">Style</label></br>
<%= select_tag :style_id, options_from_collection_for_select(Style.all, :id, :name, params[:style_id]), include_blank: true, class: "form-control" %>
<br>
</br>
<%= check_box_tag 'options[]', "picture" %>
<%= button_to '#', class: 'btn btn-default' do %>
<%= t(:find) %>
<% end %>
<% end %>
</td>
<td>
<div>
<% #bands.each do |band|%>
<div class="top-bar">
<div class="center">
<div class="info">
<div class="name"><%=band.id %></div>
<div> <%= band.zip %>, <%= band.city %> </div>
</div>
<div class="desc">
<table>
<tr>
<td>Styles</td>
<td>
<% band.styles.each do |s| %>
<%= s.style.name %>
<% end %>
</td>
</tr>
</table>
</div>
<% end %>
</td>
</tr>
</table>
models band.rb
def self.search1(style_id)
Profile.joins("...").where("style_id = ?", style_id)
end
controller.
def searchresult
if params[:style_id].present?
#bands = Band.search1 params[:style_id]
elsif params[:options]
Band.where(:options => #filtered_options)
else
#bands = Band.all
end
end
The searchresult don't show the result of the checkboxes and I have this errors:
undefined method `search1' for #<Class:0x00000008eb5548>

getting textfield value and search result after page after click on search button in ruby on rails

In my search page I have a textfield of zip code and when I enter Zip code in the textfield and click on search button the value of text field is loss and also search result is loss, what I do to stable textfield value of zip code and search result after click on search button. below is my view page:
<%= form_for :search, :url => { :method => :get, :action => :search } do |f| %>
<table width="100%">
<tr>
<td align="center" style="vertical-align:top;" width="35%">
<table>
<tr>
<td align="center">
<%= text_field_tag "tf_Zip",nil,:placeholder =>'Zip' %>
</td>
</tr>
</table>
<table>
<% if !#user.nil? %>
<% #user.each do |uzr| %>
<tr>
<td bgcolor="#CCDBE0" width="40%">
<%= image_tag #user_img.photo.url(:small),:alt => " " %>
<br/>
<div><a style="color:blue;" href = 'profile?id=<%= uzr.id %>'><%= uzr.First_Name + " " + uzr.Last_Name %></a></div>
</td>
<td bgcolor="#CCDBE0" width="60%" style="text-align:center;">
<div class='buttonblck1'><a href='searchings?id=<%= uzr.id %>'>Send Request </a></div>
</td>
</tr>
<% end %>
<% end %>
</table>
<% end %>
and below is controller page
if ( !params[:tf_Zip].blank? or params[:tf_Zip] != "" )
#user = User.find(:all,:conditions=>['"user_Zip" = ? and "id" != ? ',params[:tf_Zip], current_user.id])
end
Kindly suggest me, waiting for your reply.'
Thanks
First:
form_for is meant to be used with an instance of ActiveModel or ActiveRecord.
Use form_tag, if you want to create a form, that is not based on an object.
Second:
as you have not object, where the attributes are stored, you have to provide them yourself.
The value is defined in the second parameter of text_field_tag
i.e. in your controller:
#zip_search = params[:tf_Zip].presence
if #zip_search
#user = ...
end
and in your view:
<%= form_tag url_for( :controller => :search, :action => :search), :method => :get) do %>
<%= text_field_tag "tf_Zip", #zip_search, :placholder => 'Zip' %>
<% end %>

Resources