I wanted to know how to redirect to a template, and make it download with this template, I tried some things, using the template I had in pdf, but it is not working.
Here is how far I've been:
def download
#reversals = Reversal.where("created_at >= ? and created_at <= ?", params[:start_date], params[:end_date])
respond_to do |format|
format.xls {
send_data(:filename => 'estornos.xls', :disposition => 'attachment', :action => :index, :layout => false, :template => 'reversals/download.xls.erb', locals: {:reversals => #reversals})
}
end
end
here I call in my view:
<%= form_for :reversal, method: :post, url: download_reversals_path do %>
<%= date_select "reversal", "start_date" %>
<%= date_select "reversal", "end_date" %>
<%= submit_tag 'Download' %>
<% end %>
here is my route:
resources :reversals do
collection do
post 'download', :defaults => { :format => 'xls', :template => 'download.xls.erb'}
end
end
I have already put the type of xls in the mime_type. I already mounted the template, but I can not connect the two. The template with the method, they have the same name.
After many tests and time I found how to do:
routes:
post 'reversals/download', to: "reversals#download_pdf", as: 'download', format: 'xls'
controller:
def download_pdf
report_start_date= build_date_from_params("start_date", params[:reversal])
report_end_date= build_date_from_params("end_date", params[:reversal])
#reversals = Reversal.all.where("created_at >= ? and created_at <= ? or created_at = ? and created_at = ? ", report_start_date, report_end_date, report_start_date, report_end_date)
#start_date = report_start_date
#end_date = report_end_date
respond_to do |format|
format.html
format.xls {
response.headers['Content-Disposition'] = 'attachment; filename=" estornos-' + (Time.now).to_s + '.xls"'
render "download.xls.erb"
}
end
end
def build_date_from_params(field_name, params)
Date.new(params["#{field_name.to_s}(1i)"].to_i,
params["#{field_name.to_s}(2i)"].to_i,
params["#{field_name.to_s}(3i)"].to_i)
end
mime_types:
Mime::Type.register "application/xls", :xls
in my index view
<%= form_for :reversal, method: :post, url: download_path, format: 'xlsx' do %>
<table>
<tr>
<td>DATA DE LANÇAMENTO INICIAL:</td>
<td></td>
<td><%= date_select "reversal", "start_date" %></td>
<td rowspan="2" align="center"><%= submit_tag 'Download xlsx', class: 'btn btn-secundary' %></td>
</tr>
<tr>
<td>DATA DE LANÇAMENTO FINAL:</td>
<td></td>
<td><%= date_select "reversal", "end_date" %></td>
</tr>
</table>
<% end %>
If you are trying to download to excel, the format xls does not work, it has to be xlsx, it is only to register in the mime types the xlsx format, and in the view pass in the format: xlsx, in the routes tb create or change the one that is with the format: xlsx. Do not forget to create a view with nameoffunction.xlsx.erb.
Related
I've looked all over and can't find a solution that works.
Relevant Controller (profits_controller.rb):
def new_tabs
#market = Market.order('mjsnumber').all.first
#profit = Profit.new
profit_types_markets_products
end
def fetch_market
#market = Market.where(:id => params[:market_id]).first
form = params["form"]
respond_to do |format|
format.js { render layout: false}
end
end
Relevant View (new_tabs.html.erb):
<%= simple_form_for #profit, :remote => true do |form| %>
<% #markets.each_with_index do |market, i| %>
<%= link_to market.nick, fetch_market_path(:market_id => market.id, :form => form, profit: #profit), :remote=>'true', :id => 'navBtn' + market.id.to_s, :class => 'd-flex flex-grow-1 align-content-center text-center nav-item nav-link ' + active(i).to_s + profit_nav_font_color(market.color).to_s, "data-toggle" => "pill", "roll" => "tab", "style" => "background-color: " + market.color.to_s + ";", remote: true %>
<% end %>
<%= render :partial => 'edit_partial_form', locals: { market: #market, form: form, profit: #profit } %>
Relevant Partial (_edit_partial_form.html.erb):
<%= form.simple_fields_for :figures, :defaults => { :input_html => { :class => "floatTextBox" }}, remote: true do |figures_form| %>
<%= figures_form.input "[test]" %>
<% end %>
Relevant JS (fetch_market.erb):
$("#edit_partial_form").html("<%= escape_javascript(render partial: 'edit_partial_form', locals: { market: #market, form: form, profit: #profit } ) %>");
Routes:
get "/fetch_market" => 'profits#fetch_market', as: 'fetch_market'
It renders the partial fine, and the links appear to contain the FormBuilder information. When I click the link and add a "puts params" to the controller, it shows the params there. But then gives me an error when loading the partial in console:
ActionView::Template::Error (undefined local variable or method `form' for #<#<Class:0x00007fdbd6453648>:0x00007fdbd68db5f8>
Did you mean? fork):
1: $("#edit_partial_form").html("<%= escape_javascript(render partial: 'edit_partial_form', locals: { market: #market, form: form, profit: #profit } ) %>");
Thanks in advance.
In fetch_market method you should to edit form = params["form"] to #form = params["form"]. You was declared local var this is why your code doesnt work. And the name of the file should be fetch_market.js.erb)
I`m trying to pass related params into a model with multiselect list. I need to assing classes to lecturers by choosing a lector when creating new class entry. I checked the db and got nothing in lecturers_id column. This is my form:
<%= f.select(:lecturers_id, Lecturer.all.collect {|l| [ l.name, l.id ] }, {}, { :multiple => true }) %>
My controller:
def subject_params
params.require(:subject).permit(:name, :credit, :number_of_hours, :lecturers_id => [])
end
def create
#subject = Subject.new(subject_params)
#subject.save
redirect_to "/subjects" and return
end
And my view:
<% #lecturers.each do |lect| %>
<tr>
<td class='col-md-3'><%= lect.name %></td>
<td class='col-md-3'>
<% lect.subjects do |subj| %>
<%= subj.name %>
<% end %>
</td>
<% end %>
Assuming the association is that Subject has_many :lecturers then you would change lecturers_id to lecturers_ids:
def subject_params
params.require(:subject).permit(:name, :credit, :number_of_hours, :lecturers_ids => [])
end
Form:
<%= f.select(:lecturers_ids, ...
In case of Subject has_many :lecturers. Your form should be
<%= f.select(:lecturer_ids, Lecturer.all.collect {|l| [ l.name, l.id ] }, {}, { :multiple => true }) %>
and your subject_params should be
def subject_params
params.require(:subject).permit(:name, :credit, :number_of_hours, :lecturer_ids => [])
end
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
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}) %>
I am trying to use will_paginate for a list of items I want to display.
There is a form with drop down selections to fetch objects by status.
This is my controller
def list
#person = Person.find_by_id(session[:person_id])
params[:status] = params[:redirect_status] if params.has_key?('redirect_status')
#statuses = Peptide.statuses
#status = 'Not Ordered'
#status = params[:status] if params[:status] != nil || params[:status] == ''
#peptides = Peptide.find(:all, :conditions => ['status = ?', #status]).paginate(:per_page => 30, :page => params[:page])
if Peptide.count.zero?
flash[:notice] = "There are not any peptides entered"
redirect_to :action => 'new'
end#if zero
end
This is in the view
<form action="/peptide/create_spreadsheet_of_not_ordered" enctype="multipart/form-data" method="post">
<table class="sortable" cellpading="5" cellspacing="2" width="100">
<tr class= "header-line">
<th>SS</th>
<th>Status</th>
<th>Peptide</th>
<th>Gene</th>
<th>Submitter</th>
<th>Created</th>
<th>Updated</th>
<th>Sequence</th>
<th>Modification</th>
<th>Vendor</th>
</tr>
<% for #peptide in #peptides.reverse %>
<tr valign = "top" class= "<%= cycle('color_one', 'color_two') %>">
<!--an error here during development likely indicates that the people table has not be repopulated or
that no submitter primer is present for a primer-->
<td sorttable_customkey = 0 > <%=check_box_tag "box[]", #peptide.id %>
<td><%= #peptide.status%></td>
<td class><%= link_to #peptide.name, :action => :report, :id => #peptide.id %></td>
<td><%= gene_links(#peptide.genes) rescue 'Error'%></td>
<td><%= #peptide.submitter.name rescue "" %></td>
<td <%= sorttable_customkey_from_date(#peptide.created_at)%> >
<%= #peptide.created_at.strftime("%b %d %Y") rescue "Unknown"%>
</td>
<td <%= sorttable_customkey_from_date(#peptide.updated_at)%> >
<%= #peptide.updated_at.strftime("%b %d %Y") rescue "Unknown"%>
</td>
<td><%= #peptide.sequence%></td>
<td><%= #peptide.modifications%></td>
<td><%= #peptide.vendor%></td>
<%= buttons() %>
</tr>
<%end%>
<%= will_paginate #peptides %>
</table>
<br>
<%= submit_tag "Create Spreadsheet"%>
The default list is grouped by status ordered.
however when I select any other status and submit the form the pagination links take me back to the default status.
Please help me resolve this issue.
Thanks
Without seeing the view, it sounds like you need to add the current params as an argument to the links for the other statuses...
Update
Try adding the params to your status link:
<%= link_to #peptide.name, peptide_path(#peptide, params), :action => :report, :id => #peptide.id %>
The documentation is here.