0

我正在尝试创建一个基于 Ruby on Rails 的 Redmine 插件。我有以下查询,它获取发票期间所有问题的 time_entries 总和。

SELECT SUM( t.hours ) 
FROM time_entries t
JOIN invoices i ON t.project_id = i.project_id
WHERE t.project_id = <current project id----@project.id>
AND i.id = <billing invoice id>
AND t.updated_on >  'i.created_at'
AND t.updated_on < 'i.due_date'

如何将此查询数据存储在名为 time_spent 的发票表列中,或在发票视图中检索结果,该视图列出所有发票以及按发票 ID 进行的上述查询

我创建的模型中的关联是这样的

class Invoice < ActiveRecord::Base
  set_table_name "invoices"
    set_primary_key "invoice_id"

    belongs_to :project
    belongs_to :author, :class_name => "User", :foreign_key => "author_id"
    has_many :time_entries, :class_name => "TimeEntry", :foreign_key => "project_id"

在控制器中,我将模型称为

@invoices = Invoice.find(:all, :joins=>" INNER JOIN time_entries ON time_entries.project_id = invoices.project_id",:conditions => ["invoices.project_id = ? AND updated_on > ? AND updated_on < ?", @project.id, invoices.created_at, invoices.due_date])

我知道控制器实例变量完全搞砸了。

我在某个地方做错了。有人可以帮我解决这个问题。

4

2 回答 2

2

我假设 Rails 3+ 和 MySQL,这应该为您的 @invoices 集合中的每个项目提供一个名为“time_spent”的访问器,它将包含您正在寻找的总和。它不会将此信息保留在数据库中,但会检索它以供您查看:

Invoice.where("invoices.project_id = ? AND invoices.updated_on > ? AND invoices.updated_on < ?", @project.id, invoices.created_at, invoices.due_date).select("SELECT invoices.*, SUM( time_entries.hours ) as time_spent").joins(:time_entries).group("invoices.id")

我猜在 < Rails 3 下面:

Invoice.find(:all, 
:conditions => ["invoices.project_id = ? AND updated_on > ? AND updated_on < ?", @project.id, invoices.created_at, invoices.due_date],
:select=>"SELECT invoices.*, SUM( time_entries.hours ) as time_spent",
:joins=>[:time_entries],
:group=>"invoices.id")

(希望我输入正确。如果没有,要点是使用“选择”和“分组”方法来获得结果。)

于 2012-02-21T03:05:06.953 回答
0

让它使用以下代码。

Invoice.find(:all, :select => 'invoices.*, SUM( time_entries.hours ) as time_spent_on_issues', :joins=>" JOIN time_entries ON time_entries.project_id = invoices.project_id", :conditions => ["invoices.project_id = ? AND time_entries.updated_on > invoices.created_at AND time_entries.updated_on < invoices.due_date", @project.id])

顺便说一句,“模仿”代码帮助很大

于 2012-02-21T16:15:22.843 回答