【问题标题】:Sorting! Each blocks, attributes Ruby 1.8.7, Rails 2.3.15,排序!每个块,属性 Ruby 1.8.7,Rails 2.3.15,
【发布时间】:2013-07-29 10:44:43
【问题描述】:

我有一个管理与公共汽车相关的图像的应用程序。我的问题是我无法弄清楚如何通过特定的 BusImage 属性对每个块进行排序, :thumb_order 而不是 BusImage id。

一辆巴士有很多 BusImage。

实例变量在总线控制器中的 Show as... 下定义

@bus = Bus.find(params[:id]
@bus_images = BusImage.find(:all, :order => 'thumb_order asc')

我在 Bus Show 页面中这样调用这些实例变量:

@bus.bus_images.each do |bus_image|
  bus_image.thumb_order
  (other attributes, etc)
end 

但无论我如何更改 @bus_images 上的 :order 方法,它都不会影响视图。当我尝试在@bus 上使用该方法时,因为 Buses 没有 thumb_order 列,所以只是茫然地盯着我。

【问题讨论】:

    标签: ruby-on-rails-2 ruby-1.8.7


    【解决方案1】:

    我发现@bus_images 和你的下一个集团@bus.bus_images 之间没有任何联系。这是两个完全不同的变量。

    如果你想对你的巴士图像进行排序,试试这个:

    @bus.bus_images.sort_by(&:thumb_order').each do |bus_image|
    

    或者在您的 BusImage 模型上设置默认顺序,如 Default sort order for a rails model?

    【讨论】:

      【解决方案2】:

      我发现这种语法更容易记住,但请自行选择:

      @bus.bus_images.sort_by{|bi| bi.thumb_order}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多