Getting strange error when searching by date - ruby-on-rails

I'm trying to make report page, on which user will choose start and end date and push buttopn report. Then hidden div became visible.
My search isn't on partial.
I am using jquery_datepicker so here is my code from view:
<%= form_tag(:controller => "financial_reports", :action => "index", :method => "post")%>
<%= datepicker_input "financial_report","start_date", :dateFormat => "dd/mm/yy" %>
<%= datepicker_input "financial_report","end_date", :dateFormat => "dd/mm/yy" %>
<%= submit_tag "Run Report"%>
<% end %>
Here is my code from controller:
def search
#financial_reports = current_user.financial_reports.search(params[:start_date], params[:end_date]
render :index
end
In my Model:
def self.search(from,to)
find(:all, :conditions => [ "BETWEEN ? AND ?", from, to])
end
And it gives me error:
ActiveRecord::StatementInvalid in FinancialReportsController#search
SELECT `financial_reports`.* FROM `financial_reports` WHERE `financial_reports`.`user_id` = 67 AND (BETWEEN NULL AND NULL)
and below this:
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"AMobLLRV3aAlNn6b4Au+1nRP2AN1TLQcBCytBXhDA/g=",
"type"=>"",
"financial_report"=>{"start_date"=>"05/08/2012",
"end_date"=>"11/08/2012"},
"commit"=>"Run Report",
"method"=>"post"}
Where is my error ?

If both parameters are set at all times, you can use:
#financial_reports = current_user.financial_reports.where(:created_at => ((params[:start_date].to_date)..(params[:end_date].to_date))
If that's not the case, you could (for example) do this:
#financial_reports = current_user.financial_reports
if params[:start_date].present?
#financial_reports = current_user.financial_reports.where("created_at >= ?", params[:start_date])
end
if params[:end_date].present?
#financial_reports = current_user.financial_reports.where("created_at <= ?", params[:end_date])
end
You will probably want to encapsulate this in scopes.

Related

Kaminari Pagination with Filter

I'm using Kaminari on my site with a 'load more' button to show another six items when clicked. It works great but when I try to add a sorting order it's not passing the params to the link_to_next_page def although I can see it in the html...
The other question asked on this said to pass the params to the link_to_next_page but it doesn't make a difference.
Example: When I try to sort by lowest price > highest price the first six items are sorted but on 'load more' the sorting order is random.
Can anyone advise here??
Thanks.
Some code...
index.html.erb
<div id="offers">
<%= render :partial => #television_offers %>
</div>
<%= link_to_next_page #television_offers, 'Load More', :remote => true, :id=>"load_more_link", :params => params %> </div>
index.js.erb
$('#offers').append("<%= escape_javascript(render :partial => #television_offers)%>");
$('#load_more_link').replaceWith("<%= escape_javascript(link_to_next_page(#television_offers, 'Load More', :remote => true, :id=>'load_more_link', :params => params))%>");
application_helper.rb
def link_to_next_page(scope, name, options = {}, &block)
param_name = options.delete(:param_name) || Kaminari.config.param_name
link_to_unless scope.last_page?, name, {param_name => (scope.current_page + 1)}, options.merge(:rel => 'next') do
block.call if block
end
end
television_offers_controller.rb
def index
#television_offers = TelevisionOffer.page(params[:page]).per(6)
if params[:filter] == "large_screens"
#television_offers = #television_offers.large_size
elsif params[:filter] == "small_screens"
#television_offers = #television_offers.small_size
elsif params[:filter] == "price"
if params[:order] == "asc"
#television_offers = #television_offers.asc(:offer_price)
else
#television_offers = #television_offers.desc(:offer_price)
end
else
#television_offers = #television_offers.best
end
end
For anyone experiencing the same problem this was solved by simply updating kaminari to the latest version

Search function is not working in ruby on rails

I am creating a form for my posts search. I am doing like this ....
erb form code...
<%= form_tag '/posts/search-post', :remote=> "true" do %>
<p>
<%= text_field_tag :search, params[:search], :placeholder => "Search Posts..." %><br/>
<%= radio_button_tag :day, 1, params[:day] %>None
<%= radio_button_tag :day, 2, params[:day] %>Last Week
<%= radio_button_tag :day, 3, params[:day] %>Last Month<br/>
<%= submit_tag "Search", :onclick => "document.getElementById('spinner').style.visibility='visible';document.getElementById('postlist').style.visibility='hidden'" %>
</p>
<% end %>
root.rb
match 'posts/search-post', to: 'posts#search_post'
posts_controller.rb
def search_post
if !params[:search].blank? && params[:day].blank?
#posts = Post.paginate(page: params[:page],:per_page => 5).search(params[:search])
elsif params[:search].blank? && !params[:day].blank?
#posts = Post.paginate(page: params[:page],:per_page => 5).all if params[:day] == "1"
#posts = Post.paginate(page: params[:page],:per_page => 5).where("created_at >= ?", 1.week.ago.utc) if params[:day] == "2"
#posts = Post.paginate(page: params[:page],:per_page => 5).where("created_at >= ?", 1.month.ago.utc) if params[:day] == "3"
elsif !params[:search].blank? && !params[:day].blank?
#posts = Post.paginate(page: params[:page],:per_page => 5).search(params[:search]) if params[:day] == "1"
#posts = Post.paginate(page: params[:page],:per_page => 5).search(params[:search]).where("created_at >= ?", 1.week.ago.utc) if params[:day] == "2"
#posts = Post.paginate(page: params[:page],:per_page => 5).search(params[:search]).where("created_at >= ?", 1.month.ago.utc) if params[:day] == "3"
else
end
end
Post.rb model
def self.search(search)
search_condition = "%" + search + "%"
if search
find(:all, :conditions => ['lower(content) LIKE ? OR lower(title) LIKE ?', search_condition.downcase,search_condition.downcase])
else
find(:all)
end
end
search-post.js.erb
$("#posts_list").html("<%= escape_javascript( render(:partial => "posts") ) %>");
When I search by both keyword and day type then searching is not working (Getting all post list-items). I don't know where i am wrong. Please help.
I am not sure if you've done this intentionally, but in both your elseif and else sections in your controller, you're overwriting your search results.
For example, in your else section, you first do this:
#posts = Post.paginate(page: params[:page],:per_page => 5).search(params[:search]) if params[:day] == "1"
and then you do this:
#posts = Post.paginate(page: params[:page],:per_page => 5).where("created_at >= ?", 1.week.ago.utc) if params[:day] == "2"
Which means that the second set of results that are saved in #posts will overwrite your first set of results (what was saved in #posts in your first line).
Since you're doing an "&&" operation, then you should include your result set from your first line into the second.
One solution to your problem might be to change your Post.rb model to something like this:
def self.search(search, previous_results_set)
search_condition = "%" + search + "%"
if search
if previous_result_set.nil?
find(:all, :conditions => ['lower(content) LIKE ? OR lower(title) LIKE ?', search_condition.downcase,search_condition.downcase])
else
previous_result_set.find(:all, :conditions => ['lower(content) LIKE ? OR lower(title) LIKE ?', search_condition.downcase,search_condition.downcase])
else
find(:all)
end
end
My code might not be perfect and you can probably find a more efficient way of doing it in your code, but you get the idea. Even when you user the .where, you need to perform the .where on the previous result set, not on the Post model as a whole again. That way you will be filtering your previously filtered results.
Hope this helps.

link_to edit page default path?

I'm using Rails3 to build a simple customer information page (in table format). On this page user can edit each customer's detailed information. It's possible for each customer to have multiple records. I use link_to to get to the edit page:
<td class="edit" id="edit">edit
<%= link_to 'edit', :action => :edit, :cust_id => ci.cust_id %>
</td>
edit.html.erb:
<h1>Editing cust</h1>
<%= form_for(#cust_info) do |cust| %>
Customer: <%= cust.text_field :cust_schema %>
<%= cust.submit "Save" %>
<% end%>
In my controller, I have this:
def edit
cust_id = params[:cust_id]
#cust_info = CustInfo.find(:all, :conditions => ["cust_id = ?", cust_id])
end
The customer info page shows right. When I click the edit link, I got the error message:
ActionView::Template::Error (undefined method `cust_info_cust_info_path' for #<#<Class:0x7fb0857ce7b8>:0x7fb0857ca780>):
1: <h1>Editing cust</h1>
2:
3: <%= form_for(#cust_info) do |cust| %>
4: Customer: <%= cust.text_field :cust_schema %>
5: <%= cust.submit "Save" %>
6: <% end%>
app/views/track/edit.html.erb:3:in `_app_views_track_edit_html_erb___102324197_70198065248580_0'
Where does `cust_info_cust_info_path' come from?
EDIT: here is the code in the controller:
class TrackController < ApplicationController
def display
end
def information
end
def customerinfo
#cust_info = CustInfo.find(:all, :order=>"cust_id")
#cust_info.each do |ci|
if ci.upload_freq == 'W'
ci.upload_freq = 'Weekly'
elsif ci.upload_freq == 'M'
ci.upload_freq = 'Monthly'
end
end
end
def edit
cust_id = params[:cust_id]
#cust_info = CustInfo.find(:all, :conditions => ["cust_id = ?", cust_id])
end
end
end
Change #cust_info = CustInfo.find(:all, :conditions => ["cust_id = ?", cust_id])
to
#cust_info = CustInfo.find(cust_id)

Parameter in AJAX request

I have a view which contain multiple links:
<% a.each do |q| %>
<%= link_to "stock it",
{ :action => "stock",
:qid => q.question_id,
:qur => q.question_answers_url,
:qti => q.title } ,
:remote => true %>
<div id="<%= "stock" + q.question_id.to_s %>"></div>
<% end %>
Each link generate AJAX-request. Here is a controller:
def stock
if(!Later.where(:question_id => params[:qid]).exists?)
later = Later.new(:question_id => params[:qid], :name => params[:qti], :url => params[:qur])
later.save
end
respond_to do |format|
format.js { render :layout=>false }
end
end
Now return to the view. Each link has a 'div' with unique id='stock'. When user press the link I need to add text to specific div with corresponding id.
I have a stock.js.erb file:
$("#stock<number>").html("some text");
How can I pass div-id to stock.js.erb and how can I use it ?
Common use is to add object.id to your DOM id. That what you exactly did:
<div id="<%= "stock_#{q.question_id}" %>"></div>
Then in your controller you shoud define your question_id or your exact question:
def stock
if(!Later.where(:question_id => params[:qid]).exists?)
later = Later.new(:question_id => params[:qid], :name => params[:qti], :url => params[:qur])
later.save
end
#question_id = params[:qid]
end
Now it will be shared with your stock.js.erb file:
$("#stock_<%= #question_id %>").html("some text");

Remove a tag type from the view (involves alphabetical pagination)

I have an index view that lists all of the tags for my Entry and Message models. I would like to only show the tags for Entries in this view. I'm using acts-as-taggable-on.
Tags Controller:
def index
#letter = params[:letter].blank? ? 'a' : params[:letter]
#tagged_entries = Tagging.find_all_by_taggable_type('Entry').map(&:taggable)
#title = "Tags"
if params[:letter] == '#'
#data = Tag.find(#tagged_entries, :conditions => ["name REGEXP ?",
"^[^a-z]"], :order => 'name', :select => "id, name")
else
#data = Tag.find(#tagged_entries, :conditions => ["name LIKE ?",
"#{params[:letter]}%"], :order => 'name', :select => "id, name")
end
respond_to do |format|
flash[:notice] = 'We are currently in Beta. You may experience errors.'
format.html
end
end
tags#index:
<% #data.each do |t| %>
<div class="tag"><%= link_to t.name.titleize, tag_path(t) %></div>
<% end %>
I want to show only the taggable type 'Entry' in the view.
Any ideas? Thank you for reading my question.
SECOND EDIT:
Tags Controller:
def index
#title = "Tags"
#letter = params[:letter].blank? ? 'a' : params[:letter]
#taggings = Tagging.find_all_by_taggable_type('Entry', :include => [:tag, :taggable])
#tags = #taggings.map(&:tag).sort_by(&:name).uniq
#tagged_entries = #taggings.map(&:taggable)#.sort_by(&:id)#or whatever
if params[:letter] == '#'
#data = Tag.find(#tags, :conditions => ["name REGEXP ?",
"^[^a-z]"], :order => 'name', :select => "id, name")
else
#data = Tag.find(#tags, :conditions => ["name LIKE ?",
"#{params[:letter]}%"], :order => 'name', :select => "id, name")
end
respond_to do |format|
format.html
end
end
tags#index:
<% #data.each do |t| %>
<div class="tag"><%= link_to t.name.titleize, tag_path(t) %></div>
<% end %>
Max Williams' code works except when I click on my alphabetical pagination links. The error I'm getting [after I clicked on the G link of the alphabetical pagination] reads:
Couldn't find all Tags with IDs (77,130,115,...) AND (name LIKE 'G%') (found 9 results, but was looking for 129)
Can anyone point me in the right direction?
#taggings = Tagging.find_all_by_taggable_type('Entry', :include => [:tag, :taggable])
#tags = #taggings.map(&:tag).sort_by(&:name)
#tagged_entries = #taggings.map(&:taggable).sort_by(&:id)#or whatever

Resources