This is what I want to achieve using active query method I was asked not to do array iterations but instead use active query methods to achieve this
def index
@measurements = current_user.measurements.with_units.created_on
data = Hash.new { |h, k| h[k] = [] }
@measurements.each do |m|
data[m.unit.title] << m
end
render json: { data: data, status: :ok }
end`
This is the image of the expected JSON i wish to achieve with Active query method and here are my models for Measurement and Units
class Measurement < ApplicationRecord
belongs_to :user
belongs_to :unit
scope :with_units, -> { includes(:unit) }
scope :created_on, -> { order('created_at DESC') }
validates :value, presence: true
end
Model for Units
class Unit < ApplicationRecord
has_many :measurements
scope :with_measurements, -> { includes(:measurements) }
scope :with_user_id, ->(user) { where(user_id: user.id) }
validates :title, presence: true
end
Schema table for measurements
create_table "measurements", force: :cascade do |t|
t.integer "unit_id"
t.integer "user_id"
t.float "value"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
Schema table for Units
create_table "units", force: :cascade do |t|
t.string "title"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
CodePudding user response:
Use as_json to convert ActiveRecord collection into json.
def index
@measurements = current_user.measurements.with_units.created_on
render json: { data: @measurements.as_json(include: :unit) , status: :ok }
end