Reputation: 2139
I seriously cannot solve this syntax error:
PG::Error: ERROR: syntax error at or near "07"
LINE 1: ...WHERE (post_id = 13 AND created_at > 2012-08-27 07:13:26) ...
This is what my query looks like:
Post.where(post_filter_params_where)
def post_filter_params_where
case params[:post_filter].to_i
when 1
"post_id = #{params[:id]}"
when 2
"post_id = #{params[:id]}"
when 3
time = 24.hours.ago.utc.to_s(:db)
"post_id = #{params[:id]} AND created_at > #{time}"
else
"post_id = #{params[:id]}"
end
end
Upvotes: 0
Views: 128
Reputation: 2625
Is there a specific reason why you need to use Post.where(some_function)
, because it would make more sense to provide a method like Post.filter(params[:post_filter], params[:id])
- if you need to reuse your filter method, just write a module and include it in all related models.
Also your current code is open to SQL injection attacks. Never use ruby string interpolation to create sql strings, see http://guides.rubyonrails.org/security.html#sql-injection
Anyway, here's some code :)
class Post < ActiveRecord::Base
def self.filter(filter, post_id)
if filter.to_i == 3
where('post_id = ? AND created_at > ?', post_id, 24.hours.ago.utc)
else
where('post_id = ?', post_id)
end
end
end
Then instead of using Post.where(some_function)
in your controller, simply use Post.filter(params[:post_filter], params[:id])
. Bonus point, better use some constant to describe what 3
means.
Upvotes: 0
Reputation: 2139
I needed to prepend the querys from the function with puts
def post_filter_params_where
case params[:post_filter].to_i
when 1
puts 'post_id = ?', params[:id]
when 2
puts 'post_id = ?', params[:id]
when 3
puts 'post_id = ?', params[:id], 24.hours.ago.utc.to_s(:db)
else
puts 'post_id = ?', params[:id]
end
end
Upvotes: 0
Reputation: 160833
Use:
Post.where('post_id = ? AND created_at > ?', params[:id], 24.hours.ago.utc.to_s(:db))
The error is because you concat the where condition and missed the quote for the date.
Upvotes: 2