使用助手在 Rails 中排序

发布于 2024-11-26 11:47:29 字数 1012 浏览 1 评论 0原文

我是 ruby​​-on-rails 的新手。

我有一个计算地铁站和 ATM 之间距离的应用程序。 有两个具有多对多关系的模型:Station、Cashpoint。还有一个控制器 SHOW,它应该获取车站并显示 ATM 机,以便与车站接近。

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

         respond_to do |format|
            format.html 
         end    
    end
end

还有一个使用 Google Directions API 计算距离的助手。

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

所有这些都工作正常。

但我想知道如何通过 StationsHelper 返回的值订购 ATM?

我尝试在控制器中编写类似于以下内容的内容:

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

但它显然不起作用,因为我知道如何链接单个现金点对象 count_distance 方法参数。

也许你可以帮助我,看来我的项目结构这样做是错误的。

I'm a novice in ruby-on-rails.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凉世弥音 2024-12-03 11:47:29

试试这个:

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

Try this:

@cashpoints = @station.cashpoints.find(:all).sort_by { |c| count_distance(c.address, @station.address) }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文