What do you want to do
I want Rails to aggregate values by group (SUM) and each group's aggregate results to be defined as variables in the controller
*After that, we plan to add the defined values to JavaScript using gemgon.
·Ruby: 2.6.5
·Rails: 5.2.4.3
·DB: PostgreSQL
·DB design *For details, please refer to the following code
Parent: Record table (attribute: id, others)
child:Practice table (attributes: id, practice_item, practice_time)
p The value stored in practice_item is a string type and a fixed string
Concept
★Goal: Include Ruby variables in chart.js and display variable values in aggregate_results.html.slim
What do you need to do this?
★ The object should be the sum of all practice_time values stored for each practice_item from the records of all record tables
★ Implementation required for this purpose
1. Take out all records
2. If all records can be taken out, categorize the Practice_items in the Practice table and let them live separately
3. Calculate the total value of all the practice_time values of the separated practice_item using the sum method, etc., and use it as another object
4. Define a set of hash or array containing the total values for each practice_item.
5. Modify JS to display the defined hash or array in View
★1.2.3 (=Search and retrieve both practice_item and practice_time in the Practice table.Then aggregate practice_time with SUM function)
default aggregate_result
@record=current_user.records.includes(:practice).select("practice_item", "practice_time").group("practice_item").sum(:practice_time)
logger.info "test#{@record}"
gon.data=@record
end
So when I checked the log, it was as follows, but what should I do with 4.5 after that?I would appreciate it if you could let me know.
現 I checked the current contents on the screen, but there is no error, but it is not displayed.
Or, if you have any questions, please do not hesitate to ask me.
started POST"/__better_errors/1d27c32fbb9084fd/variables" for::1 at 2020-06-2023:40:45+0900
Started GET "/records/3/aggregate_result" for::1 at 2020-06-20 23:40:46+0900
Processing by RecordsController # aggregate_result as HTML
Parameters: {"id"=>"3"}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users". "id" = $1 ORDER BY "users". "id" ASCLIMIT $2 [["id", 3], ["LIMIT", 1]]
↳ /Users/user/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activerecord-5.2.4.3/lib/active_record/log_subscriber.rb:98
(0.6ms) SELECT SUM(practice_time) AS sum_practice_time, practice_item AS practice_item FROM "records" LEFT OUTER JOIN "PRacts" ON "PRacts"."record_id" = "records"."id "WHERE" records" . "user_id" [[PRODUCT_ID_IDERY]=1][PRODUCT_ID_ID_ID_IDERPY][PRICE] 11]
↳ app/controllers/records_controller.rb:57
test {"Multi-ball Practice"=>222, "Serve Practice"=>170, "Footwork"=>30, "All"=>22, "On-board Processing"=>120}
Rendering records/aggregate_result.html.slim with in layouts/application
Rendered records /_flash_messages.html.slim (2.0ms)
Rendered records/aggregate_result.html.slim with in layouts/application (6.1ms)
Rendered records /_header.html.slim (3.1ms)
Rendered records /_footer.html.slim (1.6ms)
Completed 200 OK in 51ms (Views:29.4ms | ActiveRecord: 5.2ms)
code
Controller
class RecordsController<ApplicationController
before_action —Authenticate_user!
def index
@q=current_user.records.ransack(params[:q])
@[email protected](distinct:true).includes(:practices).page(params[:page]).per(8)
end
def show
@record=Record.find (params[:id])
end
def new
@record=Record.new
[email protected]
[email protected]
[email protected]
end
def create
@record=Record.new(record_params)
logger.info "######{@record.inspect}"
[email protected]
flash[:success] = "Your practice has been registered."
redirect_to records_url
else
flash[:alert] = "Registration failed."
render:new
end
end
default
@record=Record.find_by (id:params[:id])
end
default update
@record=Record.find_by (id:params[:id])
[email protected](record_params)
flash[:success] = "Your practice has been updated."
redirect_to records_url
else
flash [:alert] = "Update failed."
render —edit
end
end
def destroy
record=Record.find_by (id:params[:id])
record.destroy
redirect_to root_path, notice: "Practice record deleted."
end
default_result
@record=current_user.records.includes(:practice).select("practice_item", "practice_time").group("practice_item").sum(:practice_time)
logger.info "test#{@record}"
gon.data=@record
end
private
default_user
@user=current_user|User.new
end
record_params
params.require(:record).permit(:record_id,:training_date,:learning_point, output_attributes:[:output_name,:id,:_destroy], practices_attributes:[:practice_item,:practice_time,:id,_attributes]:[:test_attributes],:[:practice_time,_attributes]:[:test_date,_attributes]:
end
end
schema.rb (partial)
ActiveRecord::Schema.define(version:2020_05_25_064157)do
create_table "practices", force: :cascade do | t |
t.string "practice_item"
t. integer "practice_time"
t.bigint "record_id"
t.datetime "created_at", null:false
t.datetime "updated_at", null:false
t.index["record_id", name: "index_practices_on_record_id"
end
create_table "records", force: :cascade do | t |
t.string "user_id"
t.text "learning_point"
t.date "training_date"
t.datetime "created_at", null:false
t.datetime "updated_at", null:false
end
aggregate_result.html.slim
= render 'records/flash_messages'
h1 Report
canvas#myPieChart
script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.js"
javascript:
varctx = document.getElementById("myPieChart");
var myPieChart = new Chart (ctx, {
type: 'pie',
data: {
labels: ["Serve Practice", "Footwork", "Third Ball Attack", "On-board Processing", "Multi-ball Practice", "All",
datasets: [{
backgroundColor: [
'rgba(255,99,132,0.2)',
'rgba (54, 162, 235, 0.2)',
'rgba (255, 206, 86, 0.2)',
'rgba (75, 192, 192, 0.2)',
'rgba (75, 192, 192, 0.2)',
'rgba(242, 68, 172, 0.2)'
],
data —gon.data
}]
},
options: {
title: {
display —true,
text: 'Breakdown of practice content'
}
}
});
= link_to 'Back to List', root_path, class: 'btn btn-primary'
The data displayed in chart.js seems to be passed in an array.
https://www.chartjs.org/docs/latest/charts/doughnut.html#data-structure
If you change the gon.data
passing data in aggregate_result.html.slim
to an array, you will see a graph.
Also, if you want to use inline Javascript in Slim, I think it would be better to expand the variables without passing them through Gon.
varctx= document.getElementById("myPieChart");
var myPieChart = new Chart (ctx, {
type: "pie",
data: {
labels:# {@record.keys},
datasets:
{
backgroundColor: [
"rgba (255, 99, 132, 0.2)",
"rgba (54, 162, 235, 0.2)",
"rgba (255, 206, 86, 0.2)",
"rgba (75, 192, 192, 0.2)",
"rgba (75, 192, 192, 0.2)",
"rgba (242, 68, 172, 0.2)",
],
data:# {@record.values},
},
],
},
options: {
title: {
display —true,
text: "Breakdown of practice content",
},
},
});
619 GDB gets version error when attempting to debug with the Presense SDK (IDE)
626 Uncaught (inpromise) Error on Electron: An object could not be cloned
577 Who developed the "avformat-59.dll" that comes with FFmpeg?
579 Understanding How to Configure Google API Key
925 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
© 2024 OneMinuteCode. All rights reserved.