2013-01-14 50 views
0

我有3个模型:运营商,产品,费率。每个承运人has_many :products和每个产品has_many :rates。我正在尝试创建一个html表格,该表格将循环显示每个产品,并仅显示最新的费率。我假设我需要将它存储在一个数组(或散列?)中,但不太清楚如何(因为我是编程新手,但学习!)。有人可以帮忙吗?如何从多个表创建阵列

回答

0

我会做模型是这样的:

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

然后这个视图:

<%= product.current_rate %> 
+0

简单而有效的..非常感谢你! –

1

最近的汇率是在您的数据库上创建的最后汇率。如果这个信息是真的,那意味着只有一个(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 %> 
+0

使用'limit',AR将带回一组模型...更好地使用'first'来直接取回对象:'scope:current_rate,order('rates.created_at DESC')。' –

+0

@AnthonyAlberto噢,更新答案。 – MurifoX

+0

谢谢..我会试试这个 –