I am struggling to amalgamate this two statements. I am working on an event app. I would like to block my users from publishing the events themselves. In order to do that i have a field in my table called "State" and i am also using the geocoder gem.
def index
if params[:search].present?
#events = Event.near(params[:search], 50, :order => :distance).where(:state => ['3', '4'])
else
#events = Event.where('until > ?', Time.zone.now)
end
end
I would like to do this....
def index
if params[:search].present?
#events = Event.near(params[:search], 50, :order => :distance).where(:state => ['3', '4'])
else
#events = Event.where('until > ?', Time.zone.now, :state => ['3', '4'])
end
end
but i get an error
ActiveRecord::PreparedStatementInvalid in EventsController#index
wrong number of bind variables (2 for 1) in: until > ?
Can you please help.....
You have only one placeholder '?', but you supply two arguments. You could do:
#events = Event.where('until > :time and state in :state', {:time => Time.zone.now, :state => ['3', '4']})
or
#events = Event.where('until > ?', Time.zone.now).where(:state => ['3', '4'])
or
#events = Event.where(:until.gt => Time.zone.now, :state => ['3', '4'])
Related
I am using sunspot 2.2.2 in my rails app for searching results,
I have this code for grouping in my model:
def self.search_products(params, currency = nil, page_uri = nil)
search_products = Sunspot.search(VariantPrice) do
group :code do
if params[:gallery_order].present?
order_by :price, params[:gallery_order].downcase.to_sym
elsif params[:new_arrival].present? || params[:name] == "new-arrivals"
order_by :product_created_at, :desc
else
if params[:fashion_type] == "fashion"
order_by :price, :asc
elsif params[:sort] != "lowhigh"
order_by :price, :asc
else
order_by :price, :asc
end
end
limit 1
end
end
and I have this code in my controller :
variant_prices = Product.search_products(params, #currency, request.original_fullpath)
#variant_prices = []
variant_prices.group(:code).groups.each do |group|
group.results.each do |result|
#variant_prices << result
end
end
#variant_prices = #variant_prices.paginate(:page => params[:page], :per_page => PER_PAGE_VALUE)
#variant_prices_count = variant_prices.group(:code).total
now I am getting the expected count that is #variant_prices_count, which is 1400 in my case, but I am getting #variant_prices count as 60 which is wrong in my case , here I was expecting to get 1400.and then I want to paginate with this result. cant understand whether it's will_paginate issue or something else.
Help!
You can get 1400 from the paginate instance also by Total entries
by this way replace count with total_entries
#variant_prices = #variant_prices.paginate(:page => params[:page], :per_page => PER_PAGE_VALUE)
#variant_prices.total_entries#it will return toal entries 1400
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.
I am fairly still new to ruby on rails and don't fully understand why I am getting the following error:
undefined local variable or method `user' for #<StatisticsController:0xb9a20d0>
The code:
class StatisticsController < ApplicationController
before_filter :authenticate, :only => [:index]
def index
#title = "Statistics"
#projects = Project.all
#data = []
Project.all.each do |project|
projdata = { 'name' => project.project_name.to_s,
'values' => [] }
['Pre-Sales','Project','Fault Fixing','Support' ].each do |taskname|
record = Effort.sum( :hours,
:joins => {:project_task => {:efforts => :user}},
:conditions => { "project_tasks.efforts.user_id" => user.id,
"project_tasks.project_id" => project.id,
"project_tasks.task_name" => taskname } )
projdata[ 'values' ].push( record )
end
#data.push( projdata )
end
end
end
Update
class StatisticsController < ApplicationController
before_filter :authenticate, :only => [:index]
def index
#title = "Statistics"
#projects = Project.all
#data = []
User.all.each do |user|
projdata = { 'name' => user.user_id.to_s,
'values' => [] }
['Pre-Sales','Project','Fault Fixing','Support' ].each do |taskname|
user = User.all
record = Effort.sum( :hours,
:joins => {:project_task => {:efforts => :user}},
:conditions => { "project_tasks.efforts.user_id" => user.id,
"project_tasks.project_id" => project.id,
"project_tasks.task_name" => taskname } )
projdata[ 'values'].push( record )
end
#data.push( projdata )
end
end
end
In string :conditions => { "project_tasks.efforts.user_id" => user.id, you call id for user object, but it is not instantiated in code above.
Your update doesn't loop over the users at all; user is now a collection of all the users. You need to iterate over the users if you want to get individual statistics for individual users.
Are you using devise? Use current_user instead of user.
Fix of your code:
User.all.each do |user|
projdata = { 'name' => user.user_id.to_s,
'values' => [] }
['Pre-Sales','Project','Fault Fixing','Support' ].each do |taskname|
record = Effort.sum( :hours,
:joins => {:project_task => {:efforts => :user}},
:conditions => { "project_tasks.efforts.user_id" => user.id,
"project_tasks.project_id" => project.id,
"project_tasks.task_name" => taskname } )
projdata[ 'values'].push( record )
end
#data.push( projdata )
end
So: removed the rogue user=User.all :)
Question: in 1 place you write user.user_id and in the other you write user.id. Is that correct?
I know how to access foreign key attributes in a scaffold index view. I can simply refer to the attributes using dot notation such as property.que.name. Given the following models:
class Priority < ActiveRecord::Base
belongs_to :que
...
end
class Que < ActiveRecord::Base
has_many :priorities
...
end
In the index view, I can do something like this to get the name value:
<td><%=h priority.que ? priority.que.name : "" %></td>
How do I do this in the jqgrid?
I tried this but the jqgrid comes back empty:
Priorities Controller:
#priorities = Priority.find(:all, :order => "position", :conditions => "multitenant_team_id = " + current_user.team.id.to_s ) do
if params[:_search] == "true"
id =~ "%#{params[:id]}%" if params[:id].present?
issue_id =~ "%#{params[:issue_id]}%" if params[:issue_id].present?
que =~ "%#{params[:que]}%" if params[:que].present?
customer =~ "%#{params[:customer]}%" if params[:customer].present?
title =~ "%#{params[:title]}%" if params[:title].present?
reporting_source =~ "%#{params[:reporting_source]}%" if params[:reporting_source].present?
priority =~ "%#{params[:priority]}%" if params[:priority].present?
product =~ "%#{params[:product]}%" if params[:product].present?
current_owner =~ "%#{params[:current_owner]}%" if params[:current_owner].present?
end
paginate :page => params[:page], :per_page => params[:rows]
order_by "#{params[:sidx]} #{params[:sord]}"
end
if request.xhr?
end
respond_to do |format|
format.html # index.html.erb
format.json { render :json => #priorities.to_jqgrid_json(
[:id, :issue_id, :que.name, :customer, :title, :reporting_source,
:priority, :product, :current_owner],
params[:page], params[:rows], #priorities.total_entries)}
format.xml { render :xml => #priorities }
end
end
Index View:
<%= jqgrid("Priorities", "priorities", "/priorities",
[
{:field => "id", :label => "ID", :width => 35, :resizable => false},
{:field => "issue_id", :label => "Issue Id"},
{:field => "que", :label => "Queue"},
{:field => "customer", :label => "Customer"},
{:field => "title", :label => "Title"},
{:field => "reporting_source", :label => "Reporting Source"},
{:field => "priority", :label => "Priority"},
{:field => "product", :label => "Product"},
{:field => "current_owner", :label => "Current Owner"}
],
{ :rows_per_page => 12, :height => 450 }
)%>
If I specify que instead of que.name, I get the data back in the grid but the Queue field shows a "#" symbol so I suspect the .to_jqgrid_json call doesn't like my syntax.
Has anyone tried this before? I hope so.
I fixed my problem. I ended up changing my find to a find_by_sql so I could do a left outer join on the ques table. I think there were a couple of issues. I think the *to_jqgrid_json* had problems with null foreign key values and I couldn't figure out how to get at the Que.name any other way. I'm using SQLServer so I had to use isnull(ques.name, '') to convert the null to empty space.
So I replaced my find as follows:
#priorities = Priority.find_by_sql ["select priorities.id id, issue_id, isnull(ques.name,' ') queue_name, customer, title, reporting_source, priority, product, current_owner from priorities left outer join ques on priorities.que_id = ques.id where priorities.multitenant_team_id = ? order by issue_id", current_user.team.id.to_s]
This introduced another problem in that find_by_sql returns an array which breaks the #priorities.total_entries call. So I had to replace it with array.count.
format.json { render :json => #priorities.to_jqgrid_json(
[:id, :issue_id, :queue_name, :customer, :title, :reporting_source, :priority, :product, :current_owner],
params[:page], params[:rows], #priorities.count)}
My grid looks great!
Edit
My grid LOOKS great but it doesn't paginate or sort. Back to the drawing board. :(
Okay, I think I fixed it for real this time.
#priorities = Priority.find(:all,
:select => "priorities.id, priorities.issue_id,
priorities.customer, priorities.title,
priorities.reporting_source, priorities.priority,
priorities.product, priorities.current_owner,
priorities.position,
isnull(ques.name,' ') queue_name",
:joins => "LEFT OUTER JOIN ques ON ques.id = priorities.que_id",
:order => "priorities.position",
:conditions => "priorities.multitenant_team_id = " + current_user.team.id.to_s ) do
I had know idea I could specify joins like this. This keeps the resultset in a format the 2dc_jqgrid plugin likes. Sorting, pagination and searching all work now. Now my grid looks good and actually works.
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