【问题标题】:Sorting in rails using helper使用助手在rails中排序
【发布时间】:2011-07-26 08:22:17
【问题描述】:

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

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

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 返回的 :value 订购 ATM?

我尝试在控制器中写一些类似于:

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

但这显然行不通,因为我知道如何链接单个 Cashpoint 对象 到count_distance方法参数。

也许你能帮助我,看来我的项目结构是错误的。

【问题讨论】:

    标签: ruby-on-rails sorting helper


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 方法 count_distance 是在 StationsHelper 中定义的,所以这不起作用(我收到错误:#<0x9b99568>
    猜你喜欢
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    • 2011-07-13
    • 2011-01-02
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多