Hitoshi Hitoshi - 2 months ago 8
Ruby Question

How can I get objects grouped by start_date and end_date in Ruby on Rails

I'm new to Rails.
Thank you so much for checking my question.

What I want to do is to extract the data ordered and grouped by start_date and end_date.

Model:

class CreateUserMedicines < ActiveRecord::Migration
def change
create_table :user_medicines do |t|
t.references :user, index: true, foreign_key: true, null: false
t.references :medicine, index: true, foreign_key: true, null: false
t.date :course_start, null: false
t.date :course_end, null: false
end
add_index :user_medicines, [:user_id, :medicine_id]
end
end


Expected view as each user is like this.

+---+------------+-------------+------------+
| | start_date | end_date | Medicines |
+---+------------+-------------+------------+
| 1 | 2016/09/11 | 2016/10/01 | A, B, C |
| 2 | 2016/09/11 | 2016/09/18 | D, E |
| 3 | 2016/09/19 | 2016/09/26 | F |
+---+------------+-------------+------------+


As each medicine (A, B, C), I want to get medicine name and id to add links.

To do this, How do I write controller and model function?

[edit:]
My desired result:

{ [ Sun, 11 Sep 2016, Sun, 17 Sep 2016 ]=> [#<UserMedicine:0x007f82c291722>, #<UserMedicine:0x007f82c291349>]


Current code and result:

record:
@user.user_medicines.group_by(&:course_start)

result:
{ [ Sun, 11 Sep 2016 ]=> [#<UserMedicine:0x007f82c291722>, #<UserMedicine:0x007f82c291349>]


Any answer will be highly appreciated.

Answer

You want to pass a block to the group_by and return an array out of the block

@user.user_medicines.group_by { |m| [m.course_start, m.course_end] }