在我正在开发的项目管理应用程序中,我目前正在开发一个用于管理票证的页面,我希望该页面包含以下内容:
- The tickets that the user has created
- The tickets that belongs to projects that the user has created
棘手的部分是在控制器中使用正确的代码,这正是我需要帮助的地方。"@users_tickets"one_answers"@owned_projects"都很好用。然而,最后一件事是创建一个数组,其中包含属于用户拥有的项目的票证,这是我需要帮助的事情(是的,我知道我对每个循环的糟糕尝试完全是错误的)。
我怎样才能实现我想要的?
票据控制器:
1. def manage
2. @users_tickets = Ticket.where(:user_id => current_user.id)
3. @owned_projects = Project.where(:user_id => current_user)
4.
5. @owned_projects.each do |project|
6. @tickets_for_owned_projects = Ticket.where(:project_id => project.id)
7. end
8. end
表格:
票表:
project_id
ticket_status_id
user_id
title
description
start_date
end_date
项目表:
user_id
title
description
start_date
end_date
如果您使用的是has_many
关联,那么它应该像一样简单
class User < ActiveRecord::Base
has_many :projects
has_many :tickets
has_many :project_tickets, through: :projects, class_name: 'Ticket', source: :tickets
#...
end
class Project < ActiveRecord::Base
has_many :tickets
#...
end
# in tickets controller
def manage
@tickets = current_user.tickets
@tickets_for_owned_projects = current_user.project_tickets
end
UPD:上述方法应该有效。我现在真的睡着了,无法确定这里出了什么问题。如果有人调查一下,我将不胜感激。
不过,这里还有另一种方法。
class User < ActiveRecord::Base
has_many :projects
has_many :tickets
def project_tickets
result = []
self.projects.each do |project|
result << project.tickets
end
result.flatten
end
#...
end