2015-09-03 163 views
0

我有這兩種模式在我的Rails應用程序:我可以在WHERE語句中使用自定義方法嗎?

create_table "projects", force: :cascade do |t| 
    ... 
    t.float "latitude", limit: 24, default: 0.0 
    t.float "longitude", limit: 24, default: 0.0 

用戶:

create_table "users", force: :cascade do |t| 
    ... 
    t.float "last_latitude",   limit: 24, default: 0.0 
    t.float "last_longitude",  limit: 24, default: 0.0111 

而且我有一個自定義類:

class CalculusAid 
    public 
    # point_one and point_two are arrays of [latitude, longitude] 

    def self.distance point_one, point_two 

    first_point_latitude, first_point_longitude = point_one 
    second_point_latitude, second_point_longitude = point_two 

    latitude_difference_in_radians = (first_point_latitude - second_point_latitude).to_radians 
    longitude_difference_in_radians = (first_point_longitude - second_point_longitude).to_radians 

    #Math stuff 
    a = Math.sin(latitude_difference_in_radians/2) * Math.sin(latitude_difference_in_radians/2) + 
    Math.cos(first_point_latitude.to_radians) * Math.cos(second_point_latitude.to_radians) * 
    Math.sin(longitude_difference_in_radians/2) * Math.sin(longitude_difference_in_radians/2); 
    c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 

    distance_in_kilometers = 6371 * c; # Multiply by 6371 to get Kilometers 
    return distance_in_kilometers 
end 
... 

我wan't做的是返回從用戶0到50公里之間的5個隨機項目,這樣做我認爲這樣的方法

class User < ActiveRecord::Base 
    def get_nearby_projects 
    @nearby_projects = User.joins(:projects).where(CalculusAid.distance([self.last_longitude],self.last_latitude][project.longitude,project.latitude]) < 50).limit(5).order("RAND()") 
    end 

但我不知道我是否可以在where語句中使用自定義方法,或者語法是否正確。

回答

-1

爲什麼不給你一個簡單的「範圍< 50公里」。 此外,您可以在Order語句中隨機撥打電話?

SELECT a,b,c, ... 
FROM table 
WHERE range < 50 
ORDER BY RAND() 
LIMIT 5; 
+0

我沒有範圍方法 –

1

這是不可能的,因爲Rails只是建立一個由MySQL執行的查詢,並從DB服務器獲得結果。這是一個原子操作,不能將lambda傳遞給MySQL來過濾結果。

但MySQL有built-in math functions

@nearby_projects = ActiveRecord::Base.connection.execute <<-SQL 
    SELECT * 
    FROM users 
    JOIN projects ON (???) -- unclear from the code you’ve pasted 
    WHERE 
    50 > 6371 * (SIN(users.last_latitude + ....... 
SQL 

希望它能幫助。

+0

我不能使用距離函數替換50> 6371 *(SIN ... –

+0

不,您應該用純SQL重寫它 – mudasobwa

+0

好的,如果沒有,更好的方式我會做 –

相關問題