给定的是具有多个项目的用户模型
每个项目属于用户
由Assigned_projects模型加入
每个项目has_many费用属于项目和用户
用户模型:
class User < ActiveRecord::Base
has_many :assigned_projects
has_many :projects, :through => :assigned_projects
has_many :created_projects, :class_name => "Project", :foreign_key => :creator_id
end
项目模型:
class Project < ActiveRecord::Base
belongs_to :user
has_many :assigned_projects
has_many :users, :through => :assigned_projects
belongs_to :creator, :class_name => "User", :foreign_key => :creator_id
has_many :expenses
end
加入模特:
class AssignedProject < ActiveRecord::Base
attr_accessible :project_id, :user_id, :position, :project
belongs_to :user, class_name: "User"
belongs_to :project, class_name: "Project"
validates :user_id, presence: true
validates :project_id, presence: true
end
费用模型:
class Expense < ActiveRecord::Base
belongs_to :project
belongs_to :user
end
总结项目的所有费用很简单: @ current_project.expenses.sum(:量)
我想列出每个用户添加的所有费用的总和 问题是如何为分配给项目的每个用户汇总所有费用。
我正在寻找类似的东西: 。@ CURRENT_USER @ current_project.expenses.sum(:量)
答案 0 :(得分:1)
我假设您正在尝试执行以下操作。如果没有,请再解释一下你的问题。
@current_project.expenses.where(user_id: @current_user.id).sum(:amount)