我如何使用主动查询方法获得同样的结果?
how do i acheive this same result using Active Query Methods?
这就是我想要使用主动查询方法实现的目标 我被要求不要进行数组迭代,而是使用主动查询方法来实现这个
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
这是我的测量和单位模型
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
使用as_json将ActiveRecord集合转换为json。
def index
@measurements = current_user.measurements.with_units.created_on
render json: { data: @measurements.as_json(include: :unit) , status: :ok }
end
这就是我想要使用主动查询方法实现的目标 我被要求不要进行数组迭代,而是使用主动查询方法来实现这个
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 这是我的测量和单位模型
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
使用as_json将ActiveRecord集合转换为json。
def index
@measurements = current_user.measurements.with_units.created_on
render json: { data: @measurements.as_json(include: :unit) , status: :ok }
end