我有三种型号:载体,产品,费率。每个运营商has_many :products和每个产品has_many :rates。我正在尝试创建一个html表,它将循环遍历每个产品,并且只显示最新的速率。我假设我需要将它存储在数组(或散列?)中,但不太确定如何存储(因为我对编程还不熟悉,但需要学习!)有人能帮忙吗?
发布于 2013-01-14 19:43:50
我会像这样做模型:
class Product < ActiveRecord::Base
def current_rate
rates.order('created_at ASC').last
end
end然后这个观点是:
<%= product.current_rate %>发布于 2013-01-14 19:28:06
最近的速率是在数据库上创建的最后一个速率。如果这个信息是真的,那就意味着一个只有一个(limit 1)行由创建日期降序(created_at DESC)命令的SQL查询将得到您想要的记录。知道了这一点,您可以在您的费率模型中创建一个范围:
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 %>https://stackoverflow.com/questions/14325069
复制相似问题