我有两种模式:
class Project < ActiveRecord::Base
has_many :ticket
attr_accessible ....
end
class Ticket < ActiveRecord::Base
belongs_to :project
attr_accessible done_date, description, ....
end
在我的ProjectsController中,我想创建一个二维哈希来为一个项目的一个变量获取所有已完成的票证(使用done_date作为键,将描述作为值)。
例如,我想要像这样的哈希:
我在寻找什么:
@tickets_of_project = ["done_date_1" => ["a", "b", "c"], "done_date_2" => ["d", "e"]]
我正在尝试的(在ProjectsController中)......
def show
# Get current project
@project = Project.find(params[:id])
# Get all dones tickets for a project, order by done_date
@tickets = Ticket.where(:project_id => params[:id]).where("done_date IS NOT NULL").order(:done_date)
# Create a new hash
@tickets_of_project = Hash.new {}
# Make a loop on all tickets, and want to complete my hash
@tickets.each do |ticket|
# TO DO
#HOW TO PUT ticket.value IN "tickets_of_project" WITH KEY = ticket.done_date ??**
end
end
我不知道我是否以正确的方式(可能使用.map而不是make where查询),但是如何通过检查索引(如果已经存在)来完成并将值放入哈希值?
Thanx:)
答案 0 :(得分:0)
之前我需要做同样的任务,因为解决方案不是很好但是应该这样做:
Ticket.where(:project_id => params[:id]).where("done_date IS NOT NULL").group_by {|t| t.done_date}.map {|k,v| [k => v.map {|vv| vv.value}] }.flatten.first