dimanche 15 août 2021

how do i acheive this same result using Active Query Methods?

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`
        

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
    

Aucun commentaire:

Enregistrer un commentaire