Rails 3 : create two dimensional hash and add values from a loop
Posted
by
John
on Stack Overflow
See other posts from Stack Overflow
or by John
Published on 2014-08-24T10:13:13Z
Indexed on
2014/08/24
10:20 UTC
Read the original article
Hit count: 366
I have two models :
class Project < ActiveRecord::Base
has_many :ticket
attr_accessible ....
end
class Ticket < ActiveRecord::Base
belongs_to :project
attr_accessible done_date, description, ....
end
In my ProjectsController I would like to create a two dimensional hash to get in one variable for one project all tickets that are done (with done_date as key and description as value).
For example i would like a hash like this :
What i'm looking for :
@tickets_of_project = ["done_date_1" => ["a", "b", "c"], "done_date_2" => ["d", "e"]]
And what i'm currently trying (in 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
I don't know if i'm in a right way or not (maybe use .map instead of make a where query), but how can I complete and put values in hash by checking index if already exist or not ?
Thanx :)
© Stack Overflow or respective owner