如何从Rails 3中的表中获取特定数据

时间:2011-05-01 19:32:48

标签: ruby-on-rails-3 models

以下是我的模特:

class Food < ActiveRecord::Base
  has_many :lists
  has_many :costs, :through => :lists
end

class List < ActiveRecord::Base #each food can have multiple lists, ordered by date
  belongs_to :food
  has_many :costs, :dependent => :destroy
  accetps_nested_attribute_for :costs, :allow_destroy => true
end

class Cost < ActiveRecord::Base #costs are nested inside of a list
  belongs_to :food
  belongs_to :list
end

这是我的架构(你需要看到的部分):

create_table "foods", :force => true do |t|
  t.integer  "food_id"
  t.string  "name"
  t.string  "type" # this is where I can choose a 'fruit' or a 'vegetable'
end

create_table "lists", :force => true do |t|
  t.integer "food_id"
  t.integer  "quarter" #this is how lists are ordered
  t.integer  "year"
end 

create_table "costs", :force => true do |t|
  t.integer  "amount" 
  t.integer "list_id"
  t.integer "food_id"
end

我想要做的是能够过滤我的表格,根据特定标准显示总费用或平均费用。因此,例如,如果我想知道一段时间内所有水果的总成本或平均成本(来自成本模型的金额属性)(按列表模型排序:季度和年份)。那更清楚了吗?感谢您的反馈到目前为止。

1 个答案:

答案 0 :(得分:1)

您需要先修复模型。您的成本属于List和Food,但在迁移中没有外键。通常,如果模型A:belongs_to模型B,模型A的表需要b_id作为外键。

一旦你修复了它,因为你想要一个聚合,你将不得不根据具有聚合值的模型构建一个查询 - 在本例中是Cost。您希望将其限制为仅包含与具有特定属性的Food相关联的成本 - 因此请使用此方法链接(假设您使用的是Rails 3):

# average cost of all fruit
Cost.includes(:food).where('foods.type = ?', 'fruit').average(:amount)

要按年份和季度限制这一点会变得有点复杂,但工作方式相同,但为了给您提供可靠的建议,您需要先修复模型。我建议阅读这两个指南:

修改

编辑完成后,试试这个(未经测试):

Cost.includes(:food, :list).where('foods.type = ? AND lists.year = ? AND lists.quarter = ?', 'fruit', 2011, 1).average(:amount)