Ruby on Rails Thursday, February 4, 2016

Hi,

On Fri, Feb 5, 2016, at 00:30, John Sanderbeck wrote:
> I am new to Rails and Ruby and am having a difficult time building the
> data needed for a Highchart. I am struggling with the syntax to map a
> pair of hashes to an array. Let me try and explain:
>
> I have a table of "initiatives" which contains basically an ID and a
> Name.
>
> Then I have a table "trainings" that has the initiative_id field to map
> to the initiative table
>
> What I am trying to do is create a method that pulls the Initiative name
> and the count of records from the trainings, and returns an array with
> [[name,count],[name,count]]
>
> What I have been trying is this
>
> def training_count_by_initiative()
> initiative_name = Initiative.all.select("id,name")
> training_count = Training.group(:initiative_id).count
> initiative_name.map do |initiative|
> ??? This is the part I am struggling with
> end
> end
>
> I tried following Railscasts #223 but can't seem to get the mapping to
> work.
>


You want the map to return an array with content of [name, count]

So you need to get name and count from inside the map.

`initiative` variable already contains the name so the first part of
array is simple, it's just `initiative.name` (`[initiative.name, ...]`).

And as for the count, it's inside `training_count`. The query you have
should return a hash with structure `{:id => :count}`. To access count
of each id, it's just `training_count[<insert_id>]`. In same spirit with
previous part, `training_count[initiative.id]` should do the trick.

Combined, all you need is one line of `[initiative.name,
training_count[initiative.id]]`.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/1454600848.4121194.511985170.29B9C166%40webmail.messagingengine.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment