开发者

Sorting in rails using helper

开发者 https://www.devze.com 2023-03-23 10:40 出处:网络
I\'m a novice in ruby-on-rail开发者_JS百科s. I have an applications counting distance between metro station and a ATM.

I'm a novice in ruby-on-rail开发者_JS百科s.

I have an applications counting distance between metro station and a ATM. There's two models with many-to-many relation: Station, Cashpoint. And there's a controller SHOW, that should get the station and show ATMs in order there's proximity to the station.

class StationsController < ApplicationController
    def show
        @station = Station.find(params[:id])
        @cashpoints = @station.cashpoints.find(:all)

         respond_to do |format|
            format.html 
         end    
    end
end

Also there's a helper that counts distance using Google Directions API.

module StationsHelper
    def count_distance(origin,destination)
         ...
        return {:text => ... # 1 min
                , :value => ... # 60 (seconds)
                }
    end
end

All this works properly.

But I'm wondering how to order ATMs by :value returned by StationsHelper?

I tried to write something in controller similar to:

@cashpoints = @station.cashpoints.find(:all, 
:order => count_distance(@station.address, cashpoint.address)[:value])

But it's evidently doesn't work 'cause I have know idea how to link single cashpoint object to count_distance method parameter.

May be you can help me, it appears that my project structure is wrong to do this.


Try this:

@cashpoints = @station.cashpoints.find(:all).sort_by { |c| count_distance(c.address, @station.address) }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号