Devise Gem and the Geocoder Gem - ruby-on-rails-3

I am using geocoder and the devise gem. And i am trying to get coupons near user's location
Coupon Model
def index
if params[:search].present?
#coupons = Coupon.near([user_long, user_lat], 50, :order => :distance)
else
#coupons = Coupon.all
end
end
Application Helper
I have defined the user_long and user_lat
def user_long
current_user.longitude
end
def user_lat
current_user.latitude
end
Devise Gem
I have tried to use the devise gem helper to get the values like so
Coupon Model
def index
if params[:search].present?
#coupons = Coupon.near([current_user.longitude, current_user.latitude], 50, :order => :distance)
else
#coupons = Coupon.all
end
end
I am hitting the walls and celling with this. Can someone help out, i know this is newbie question for but i can't solve it so save my life?

You are not seeing anything on the index page because your #coupons array is empty:
#coupons = Coupon.near([current_user.longitude, current_user.latitude], 50, :order => :distance)
In development log (in the same window where rails server is running, if you are running the rails server from console), you should check out the SQL query generated for CouponsController#index action.
Assuming you defined your 'near' query like this:
class Coupon
scope :near, lambda { |longitude, latitude| some logic...
end
You can debug this 'near' method using "rails console" like this:
rails console
> Coupon.near(10, 20)
etc..

My mistake was that i that i had the longitude before that latitude, It was taking away the logic
This works.
def index
#coupons = Coupon.near([current_user.latitude, current_user.longitude], 50, :order => :distance)
end

Related

Using Twilio in Rails 4 - Uninitialized Constant Error

I am trying to integrate Twilio with my Rails 4 app. I followed a tutorial, but I keep getting an error. Right now I am getting an Uninitialized Constant Error. I provided the code below. Thanks in advance.
Routes.rb
get '/share_over_sms' => 'listing_collections#share_over_sms'
Listing Collection Model
require "messenger"
def clean_number
client_number = self.client_number.scan(/\d+/).join
client_number[0] == "1" ? client_number[0] = '' : client_number
client_number unless client_number.length != 10
end
Messenger Module
module Messenger
def send_sms(number)
twilio_sid = "ENV['TWILIO_ACCOUNT_SID']"
twilio_token = "ENV['TWILIO_AUTH_TOKEN']"
#twilio_client = Twilio::REST::Client.new twilio_sid, twilio_token
from = '+1xxxxxxxxxx'
message = #twilio_client.account.sms.messages.create(
:from => from,
:to => "+1"+number,
:body => "This is a test message."
)
end
end
Listing Collections Controller
def share_over_sms
#client_phone = ClientPhone.new(listing_collection_params)
#client_phone.send_sms(#client_phone.clean_number)
redirect_to :back
end

how can I hide resources?

I want to create a page where it shows the resource created by other users but hide the resources created by current_user. is there a method or certain way in which I can do so?
class ExamplesController < ApplicationController
def index
#examples = Example.all.order("created_at DESC")
#creator_examples = Example.where(creator: current_user).order("created_at DESC") <---hide this!!!
end
You can simply manipulate your where clause into something like this:
def index
#examples = Example.all.order("created_at DESC")
#creator_examples = #examples.where.not(id: current_user.id)
end
This is for rails 4, if you're using rails 3
#creator_examples = Example.where("id != ?", current_user.id)
Note -> Example.all in rails 3 returns an array so you can't chain it with where

How to convert postgresql column into a float for a scoped search in rails

I am trying to search my postgresql db in rails. I followed the Railscasts #111 Advanced Search tutorial and it is working for the name and category of my items column in plain text. However, I want to set a min/max price on my search as well which is where I come into my problem. In my db my price is stored as a string in the format "AU $49.95". Can I convert this into a float on the fly in my scoped search? If so how? If not, what should I do?
Here is the code:
search.rb
class Search < ActiveRecord::Base
attr_accessible :keywords, :catagory, :minimum_price, :maximum_price
def items
#items ||= find_items
end
private
def find_items
scope = Item.scoped({})
scope = scope.scoped :conditions => ["to_tsvector('english', items.name) ## plainto_tsquery(?)", "%#{keywords}%"] unless keywords.blank?
scope = scope.scoped :conditions => ["items.price >= ?", "AU \$#{minimum_price.to_s}"] unless minimum_price.blank?
# scope = scope.scoped :conditions => ["items.price <= ?", "AU \$#{maximum_price.to_s}"] unless maximum_price.blank?
scope = scope.scoped :conditions => ["to_tsvector('english', items.catagory) ## ?", catagory] unless catagory.blank?
scope
end
end
searches_controller.rb
class SearchesController < ApplicationController
def new
#search = Search.new
end
def create
#search = Search.new(params[:search])
if #search.save
redirect_to #search, :notice => "Successfully created search."
else
render :action => 'new'
end
end
def show
#search = Search.find(params[:id])
end
end
Thanks for reading this far!
Use the data type numeric or money for exact numerical calculation without rounding errors - and sorting as a number (not as text).
Converting string literal to numeric should not be a performance problem at all.

Rails 3 - Merge query options

I have this method form a Rails 2.3.4 app:
def self.find_all_colored(query, options={})
finder_options = {:conditions => "color = #{query}"}.merge(options)
Car.find(:all, finder_options)
end
With which I can do:
Car.find_all_colored("red", :limit => 5)
But I am having a really bad time trying to get that to work in Rails 3.1.1, by now I can make it work but without the .merge(options), if I add that part:
def self.find_all_colored(query, options={})
Car.where("color = #{query}").merge(options)
end
I get this error:
undefined method `default_scoped?' for {:limit=>5}:Hash
I've googled and searched in stackoverflow.com but no luck...thanks!
Try the following:
def self.find_all_colored(query, options={})
self.all({:conditions => {:color => query}}.merge(options))
end

Will_Paginate and order clause not working

I'm calling a pretty simple function, and can't seem to figure out whats going on. (I'm using rails 3.0.3 and the master branch of 'will_paginate' gem). I have the following code:
results = Article.search(params) # returns an array of articles
#search_results = results.paginate :page => params[:page], :per_page=>8, :order => order_clause
No matter what I make the order_clause (for example 'article_title desc' and 'article_title asc'), the results are always the same in the same order. So when I check using something like #search_results[0], the element is always the same. In my view, they are obviously always the same as well. Am I totally missing something?
I'm sure its something silly, but I've been banging my head against the wall all night. Any help would be much appreciated!
Edited to Add: The search clause does the following:
def self.search(params)
full_text_search(params[:query].to_s).
category_search(params[:article_category].blank? ? '' : params[:article_category][:name]).
payout_search(params[:payout_direction], params[:payout_value]).
length_search(params[:length_direction], params[:length_value]).
pending.
distinct.
all
end
where each of these guys is a searchlogic based function like this:
#scopes
scope :text_search, lambda {|query|
{
:joins => "INNER JOIN users ON users.id IN (articles.writer_id, articles.buyer_id)",
:conditions => ["(articles.article_title LIKE :query) OR
(articles.description LIKE :query) OR
(users.first_name LIKE :query) OR
(users.last_name LIKE :query)", { :query => "%#{query}%" }]
}
}
scope :distinct, :select => "distinct articles.*"
#methods
def self.payout_search(dir, val)
return no_op if val.blank?
send("payment_amount_#{dir.gsub(/\s+/,'').underscore}", val)
end
def self.length_search(dir, val)
return no_op if val.blank?
send("min_words_#{dir.gsub(/\s+/,'').underscore}", val)
end
Thanks.
If you look at the example from the will_paginate github page you can spot one important difference between their use of the :order clause and yours:
#posts = Post.paginate :page => params[:page], :order => 'created_at DESC'
This calls paginate on the Post object (with no objects being selected yet - no SQL has been executed before paginate comes along). This is different in your example: as you state in the first line of code "returns an array of articles". The simplest I can come up with showing the problem is
results = Model.limit(5).all
#results = results.paginate :order => :doesnt_matter_anymore
won't sort, but this will:
results = Model.limit(5)
#results = results.paginate :order => :matters
It should suffice to take the all out of the search method. It makes ActiveRecord actually perform the SQL query when calling this method. Will_paginate will do that for you when you call paginate (if you let it...). Check out the section on Lazy Loading in this post about Active Record Query Interface 3.0