Rails downloading empty csv file - ruby-on-rails

I have a problem with Downloading csv files from my rails app.
First the controller looks like this;
def report
#report = SentMessage.where('user_id = ? AND created_at <= ? AND created_at >= ?', current_user.id, params[:before], params[:after]).order('created_at Desc')
respond_to do |format|
format.html
format.csv do
response.headers["Content-Type"] = "text/csv; charset=UTF-8; header=present"
response.headers["Content-Disposition"] = "attachment; filename=sent_messages.csv"
end
end
end
then my report.csv.erb file looks like this;
<%= provide(:title, "Sent Messages") %>
<div>
<div class="panel radius"> <h2 class="text_center">Sent Messages</h2></div>
<table class="table table-striped table-bordered table-hoverlarge-12 radius columns large-centered" id="sent_table">
<thead>
<tr>
<th>To</th>
<th>From</th>
<th>Message</th>
<th>Delivery Report</th>
<th>cost</th>
<th>Time</th>
</tr>
</thead>
<tbody>
<% #report.each do |message| %>
<tr>
<td><%= message.to %></td>
<td><%= message.from %></td>
<td><%= message.message %></td>
<td><%= message.delivery %></td>
<td><%= message.cost %></td>
<td><%= message.created_at.to_datetime.strftime("%b %d, %Y %I:%M%P") %></td>
</tr>
<% end %>
</tbody>
</table>
</div>
</div>
When i click the download link, the downloaded file is just empty besides the headers as show in the report.csv.erb file.
What could be the problem?

I simply had to change the link to the download from;
to
<%= link_to "Download CSV", params.merge(format: "csv"), class: "button radius" %>
And it worked.

Do like that may be work for you.
def report
#report = SentMessage.where('user_id = ? AND created_at <= ? AND created_at >= ?', current_user.id, params[:before], params[:after]).order('created_at Desc')
respond_to do |format|
format.html
format.csv{
response.headers["Content-Type"] = "text/csv; charset=UTF-8; header=present"
response.headers["Content-Disposition"] = "attachment; filename=sent_messages.csv"}
end
end

Related

unable to convert unpermitted parameters to hash rails

I was trying to add csv for my the search results but it throws error telling unpermitted params. What params should i pass in the csv link? So that csv would download the only the search results.
ReportsController
def revenue_search
#bookings = Booking.complete.order("created_at DESC")
date = "1-#{params['date']['month']}-#{params['date']['year']}"
date = Date.parse(date)
#bookings = #bookings.where(created_at: date.beginning_of_month..date.end_of_month)
#per_page = params[:per_page] || Booking.per_page || 20
#bookings = #bookings.paginate( :per_page => #per_page, :page => params[:page])
if params[:currency].present?
#bookings = #bookings.where(currency: params[:currency])
end
respond_to do |format|
format.html
format.csv { send_data #bookings.revenue_csv }
end
end
Model
def self.revenue_csv
attributes = %w{ total value deposit balance }
CSV.generate(headers: true) do |csv|
csv << attributes
all.each do |booking|
csv << attributes.map{ |attr| booking.send(attr) }
end
end
end
revenue.html.erb
<%= form_tag revenue_search_path, :method => 'get' do %>
<%= select_tag(:currency, options_for_select(["USD", "GBP"]), class: "form-control custom-select" , :prompt => 'By Office' ) %>
<%= select_month((#selected_date || Date.today), {}, class:"custom-select", :prompt => 'By Month')%>
<%= select_year((#selected_year || Date.today.year), {}, class:"custom-select" )%>
<%= submit_tag "Search", name: nil , class: "btn btn-info" %>
<% end %>
<table id="demo-foo-addrow" class="table m-t-30 table-hover no-wrap contact-list no-paging footable-loaded footable" data-page-size="2">
<thead>
<tr>
<th class="footable-sortable">Total No of students<span class="footable-sort-indicator"></span></th>
<th class="footable-sortable">Value of courses sold<span class="footable-sort-indicator"></span></th>
<th class="footable-sortable">Total Deposits<span class="footable-sort-indicator"></span></th>
<th class="footable-sortable">Balance payments<span class="footable-sort-indicator"></span></th>
</tr>
</thead>
<tbody>
<tr>
<td><%= #bookings.count %></td>
<td><%= #bookings.count %></td>
<td><%= #bookings.sum{|x| (x.payment_gross.to_f)} %></td>
<td><%= #bookings.sum{|x| (x.course&.course_fee || x.event&.course_fee).to_f - x.payment_gross.to_f }.to_f %></td>
</tr>
</tbody>
</table>
<p> Download: <%= link_to "CSV", revenue_search_path(format: "csv" , params: params ) %> </p>
logs:
ActionView::Template::Error (unable to convert unpermitted parameters to hash):
42: </div>
43: </div>
44: </div>
45: <p> Download: <%= link_to "CSV", revenue_search_path(format: "csv" , params: params ) %> </p>
app/views/reports/revenue_search.html.erb:45:in `_app_views_reports_revenue_search_html_erb___71501213_135144540'
You can use to_unsafe_h
revenue_search_path(format: "csv" , params: params.to_unsafe_h)

Rails syntax error </div>

I am trying to set "edit" function for a simple CMS. I can make it to create/delete, but it just won't let me "edit".
here is the error message:
SyntaxError in SectionsController#edit
app/views/sections/edit.html.erb:42: syntax error, unexpected keyword_ensure, expecting keyword_end
Extracted source (around line #42):
40
41
when I checked my edit.html.erb. it seems fine?
'index'}, :class => 'back-link') %>
<div class="sections edit">
<h2>Update Sections</h2>
<%= form_for(:two, :url => {:action => 'update', :id => #one.id}) do |f| %>
<table summary="Section form fields">
<% #one.each do |f| %>
<tr>
<th>Name</th>
<td><%= f.text_field(:name) %></td>
</tr>
<tr>
<th>Position</th>
<td><%= f.text_field(:position) %></td>
</tr>
<tr>
<th>Visible</th>
<td><%= f.text_field(:visible) %></td>
</tr>
<tr>
<th>content_type</th>
<td><%= f.text_field(:content_type) %></td>
</tr>
<tr>
<th>content</th>
<td><%= f.text_field(:content) %></td>
</tr>
<tr>
<th>page_id</th>
<td><%= f.text_field(:page_id) %></td>
</tr>
</table>
<div class="form-buttons">
<%= submit_tag("Update Section") %>
</div>
<% end %>
</div>
Here is the controller:
class SectionsController < ApplicationController
def index
#one = Section.all
end
def show
#one = Section.find(params[:id])
end
def new
#one = Section.new
end
def create
#one = Section.new(section_params)
if #one.save
flash[:notice] = "Section created successfully!"
redirect_to(:action => 'index')
else
render('new')
end
end
def edit
#one = Section.find(params[:id])
end
def update
#one = Section.find(params[:id])
if #one.update_attributes(section_params)
flash[:notice] = "Subject updated successfully!"
redirect_to(:action => 'show', :id =>#one.id)
else
render('edit')
end
end
def delete
#one = Section.find(params[:id])
end
def destroy
subject = Section.find(params[:id]).destroy
flash[:notice] = "Subject deleted successfully!"
redirect_to(:action => 'index')
end
private
def section_params
params.require(:two).permit(:id,:name,:position,:visible,:page_id,:content,:content_type)
end
end
Thanks so much!!
Thanks #Pavan, #MarsAtomic and #Mandeep ! I found the issue: <% #one.each do |f| %>. I don't really need this line. If I need it, I need a end code for this.
In my case, I don't, so I go ahead deleted this line, and it worked now!
thanks again everyone!

Rails 3.2 config.cache_classes = true results blank values in view

I have a template (show.html.erb) which submits adjustment requests. Also in the template I have a table that breaks down Pending Adjustments and Completed Adjustments that show you information about the adjustment you just submited. EX. type, reason, created at.
When I set config.cache_classes = true in my environments/development.rb the Pending Adjustments and Completed Adjustments table the values dont show except for the created at timestamp. The type or reason do not show. If I set config.cache_classes = false everything appears. I've also set config.action_view.cache_template_loading = false and still get the same results empty table values.
I am trying to get it to work with config.cache_classes = true because in production I need the caching to be turned on for other things.
controllers/print_cost_controller.rb
class PrintCostController < ApplicationController
def show
#printcost = PrintCost.find(params[:id])
#order = Core::Order.find(params[:id])
authorize! :show, #order
respond_to do |format|
format.html { render :show }
end
end
end
models/printcost.rb
class PrintCost < ActiveResource::Base
self.site = ENV["PRINT_COST_URL"]
#headers = { 'Authorization' => "Token token=#{ENV['PRINT_COST_TOKEN']}" }
end
show.html.erb
<% if !#printcost.adjustments.empty? %>
<div class="adjustments_pending">
<h4 class="printcost">Pending Adjustments</h4>
<table class="table">
<tr>
<th>Requested On</th>
<th>Reason</th>
<th>Type</th>
<th></th>
</tr>
<% #printcost.adjustments.each do |adjustment| %>
<% if adjustment.completed_at == nil %>
<tr>
<td><%= DateTime.parse(adjustment.created_at).in_time_zone("Eastern Time (US & Canada)").strftime("%^b-%d-%y %I:%M:%S %P") %></td>
<td><%= adjustment.explanation %></td>
<td><%= adjustment.adjustment_type %></td>
<td><%= link_to 'X', remove_adjustment_path(adjustment.id), :method => :delete, :class => "badge", "data-title" =>"Cancel Request" %></td>
</tr>
<% end %>
<% end %>
</table>
</div>
<div class="adjustments_completed">
<h4 class="printcost">Completed Adjustments</h4>
<table class="table">
<tr>
<th>Requested On</th>
<th>Reason</th>
<th>Type</th>
<th>Note</th>
</tr>
<% #printcost.adjustments.each do |adjustment| %>
<% if adjustment.completed_at %>
<tr>
<td><%= DateTime.parse(adjustment.completed_at).in_time_zone("Eastern Time (US & Canada)").strftime("%^b-%d-%y %I:%M:%S %P") %></td>
<td><%= adjustment.adjustment_type == "Tax" ? "$#{adjustment.adjustment_cost} - #{adjustment.explanation}" : adjustment.explanation %></td>
<td><%= adjustment.adjustment_type %></td>
<td><%= adjustment.note %></td>
</tr>
<% end %>
<% end %>
</table>
</div>
<% end %>
Any ideas on why this is happening?
I figured out the problem. It was an issue with another model I had called Adjustments. Had to rename some things.

Tabbed menus broke my geocoder search functionality

I'm fairly new to Ruby on Rails, making a directory type of website as a personal project to learn.
In my app, I implemented Geocoder search so the user can search for places/locations near them, the search worked perfect. But then when I added tabbed menus to categorize what type of places are available it broke the search.
I think I know why it's broken but not sure how to fix it. The tabs are showing the #schools, #restaurants, and #businesses variables, how can I get the tabs to show the search results and not those variables? Those variables should only show up when there is no search executed, but they also show up when the search is executed.
Here's my code:
Places Controller:
class PlacesController < ApplicationController
before_filter :authenticate_user!, except: [:index]
def index
if params[:search].present?
#places = Place.near(params[:search], 50, :order => :distance)
else
#places = Place.all
end
#schools = Place.where("category = ?", "School")
#restaurants = Place.where("category = ?", "Restaurant")
#businesses = Place.where("category = ?", "Business")
end
Places Index.html.erb:
<% if user_signed_in? %>
<div class="row">
<h2>Newly Added Places</h2>
<%= form_tag places_path, :method => :get do %>
<%= text_field_tag :search, params[:search], placeholder: "Enter your zipcode or city", class: "search-query" %>
<%= submit_tag "Search Nearby", :name => nil, class: "btn"%>
<% end %>
<ul class="nav nav-tabs">
<li>Schools</li>
<li>Restaurants</li>
<li>Businesses</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="tab1">
<%= render :partial => "places", :locals => {:places_container => #schools} %>
</div>
<div class="tab-pane" id="tab2">
<%= render :partial => "places", :locals => {:places_container => #restaurants} %>
</div>
<div class="tab-pane" id="tab3">
<%= render :partial => "places", :locals => {:places_container => #businesses} %>
</div>
</div>
</div>
<br />
<% else %>
<%= render 'static_pages/home' %>
<% end %>
Places partial(_places.html.erb):
<table class="table table-hover table-condensed">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Address</th>
<th>State</th>
<th>City</th>
<th>Type</th>
<th>Website</th>
</tr>
</thead>
<% places_container.each do |place| %>
<tr>
<th><%= image_tag place.image(:medium)%></th>
<th><%= link_to place.name, place %></th>
<td><%= place.address %></td>
<td><%= place.state %></td>
<td><%= place.city %></td>
<td><%= place.category %></td>
<td><%= place.website %></td>
<% if current_user.admin? %>
<td><%= link_to 'Edit', edit_place_path(place) %></td>
<td><%= link_to 'Destroy', place, method: :delete, data: { confirm: 'Are you sure?' } %></td>
<% end %>
</tr>
<% end %>
</table>
Your tabbed results are ignoring the search parameter because you aren't using the #places relation built from the search parameter. To fix, change this code:
def index
if params[:search].present?
#places = Place.near(params[:search], 50, :order => :distance)
else
#places = Place.all
end
#schools = Place.where("category = ?", "School")
#restaurants = Place.where("category = ?", "Restaurant")
#businesses = Place.where("category = ?", "Business")
end
to:
def index
if params[:search].present?
#places = Place.near(params[:search], 50, :order => :distance)
else
#places = Place.scoped # use 'scoped', not 'all', to avoid triggering the query immediately
end
#schools = #places.where("category = ?", "School")
#restaurants = #places.where("category = ?", "Restaurant")
#businesses = #places.where("category = ?", "Business")
end

rails 3.2 ajax live search

I'm still a Rails-Learner and getting desperate about implementing an ajax live search. The search seems to work on submitting, but not on keyup. Can't figure out why...
index.html.erb
<%= form_tag contacts_path, :method => 'get', :id => "contacts_search" do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<div id="cresults_div"><%= render 'cresults' %></div>
<% end %>
<%= link_to 'New Contact', new_contact_path %>
contacts_controller.rb
def index
#contacts = Contact.search(params[:search])
respond_to do |format|
format.html # index.html.erb
format.json { render json: #contacts }
end
end
index.js.erb
$("#cresults_div").html("<%= escape_javascript(render("cresults")) %>");
contact.rb
def self.search(search)
if search
where('last_name LIKE ?', "%#{search}%")
else
scoped
end
end
contacts.js.coffee
jQuery ->
# Ajax search on submit
$('#contacts_search').submit( ->
$.get(this.action, $(this).serialize(), null, 'script')
false
)
# Ajax search on keyup
$('#contacts_search input').keyup( ->
$.get($("#contacts_search").attr("action"), $("#contacts_search").serialize(), null, 'script')
false
)
_cresults.html.erb
<%= hidden_field_tag :direction, params[:direction] %>
<%= hidden_field_tag :sort, params[:sort] %>
<h1>Listing contacts</h1>
<table>
<tr>
<th>Salutation</th>
<th>First name</th>
<th>Last name</th>
<th>Stree</th>
<th>Street no</th>
<th>Zip</th>
<th>City</th>
<th>State</th>
<th>Country</th>
<th>Phone</th>
<th>Email</th>
<th></th>
<th></th>
<th></th>
</tr>
<% #contacts.each do |contact| %>
<tr>
<td><%= contact.salutation %></td>
<td><%= contact.first_name %></td>
<td><%= contact.last_name %></td>
<td><%= contact.stree %></td>
<td><%= contact.street_no %></td>
<td><%= contact.zip %></td>
<td><%= contact.city %></td>
<td><%= contact.state %></td>
<td><%= contact.country %></td>
<td><%= contact.phone %></td>
<td><%= contact.email %></td>
<td><%= link_to 'Show', contact %></td>
<td><%= link_to 'Edit', edit_contact_path(contact) %></td>
<td><%= link_to 'Destroy', contact, confirm: 'Are you sure?', method: :delete %></td>
</tr>
<% end %>
</table>
also tried to additional add
application.js
$(function() {
$("#contacts_search input").keyup(function() {
$.get($("#contacts_search").attr("action"), $("#contacts_search").serialize(), null, "script");
return false;
});
});
But the live search won't start on typing... why?
In this particular case I had to remove the
respond_to do |format|
format.html # index.html.erb
format.json { render json: #contacts }
end
Block from the index-Method in the contacts controller

Resources