0

我有 3 个模型:运营商、产品、费率。每个运营商has_many :products和每个产品has_many :rates。我正在尝试创建一个 html 表格,该表格将遍历每个产品并仅显示最新汇率。我假设我需要将它存储在一个数组(或哈希?)中,但不太确定如何(因为我是编程新手,但正在学习!)。有人可以帮忙吗?

4

2 回答 2

1

最新汇率是在您的数据库上创建的最后汇率。如果此信息属实,则意味着 SQL 查询仅获取limit 1按创建日期降序 ( ) 排序的 ( created_at DESC) 行将获得您想要的记录。了解这一点后,您可以在费率模型中创建范围:

scope :current_rate, order('rates.created_at DESC').limit(1).first
# As @AntohnyAlberto said, limit would bring an array, so you may use .first on the results
# Or you can use just .first, as it would bring only the first one
scope :current_rate, order('rates.created_at DESC').first

并在您的视图中在您的产品循环中使用此范围:

  <%= product.rate.current_rate %>
于 2013-01-14T19:28:06.937 回答
0

我会做这样的模型:

class Product < ActiveRecord::Base
  def current_rate
    rates.order('created_at ASC').last
  end
end

然后在视图中:

<%= product.current_rate %>
于 2013-01-14T19:43:50.443 回答