我有一个很长的方法来创建一组团队。每个团队与几个用户关联。方法完成并确定了团队之后,我正在尝试使用尽可能少的数据库调用来保存所有这些信息。
协会:
class Team < ApplicationRecord
belongs_to :objective
belongs_to :consultancy
has_one :seminar,:through => :consultancy
belongs_to :consultant,class_name: "Student"
has_and_belongs_to_many :users
end
class User < Application
attr_accessor :remember_token,:activation_token,:reset_token
before_save :downcase_stuff
before_validation :check_title,:check_user_number,:check_username,:check_password
before_create :create_activation_digest
after_create :update_last_login
has_and_belongs_to_many :teams
end
这就是我要保存它们的方式:
these_teams = []
@teams.each_with_index do |team,index|
these_teams[index] = Team.new(:consultancy_id => @consultancy.id,:consultant_id => team[:consultant_id],:objective_id => team[:objective_id],:bracket => team[:bracket])
these_teams[index].user_ids = team[:user_ids]
end
Team.transaction do
these_teams.each do |this_team|
this_team.save!
end
end
这是我在本地服务器上运行此代码时的sql阅读示例。这仅适用于其中一个团队。我要保存的所有十二支球队都重复了所有这些操作。
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."username" = ? LIMIT ? [["username","jo16"],["LIMIT",1]]
User Exists (0.1ms) SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER(?) AND ("users"."id" != ?) LIMIT ? [["email","example-22@railstutorial.org"],["id",16],1]]
Student Exists (0.1ms) SELECT 1 AS one FROM "users" WHERE "users"."type" IN ('Student') AND "users"."username" = ? AND ("users"."id" != ?) LIMIT ? [["username",1]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."username" = ? LIMIT ? [["username","kg19"],"example-25@railstutorial.org"],19],"es32"],1]]
User Exists (0.2ms) SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER(?) AND ("users"."id" != ?) LIMIT ? [["email","example-38@railstutorial.org"],32],1]]
Student Exists (0.2ms) SELECT 1 AS one FROM "users" WHERE "users"."type" IN ('Student') AND "users"."username" = ? AND ("users"."id" != ?) LIMIT ? [["username",1]]
SQL (0.1ms) INSERT INTO "teams" ("consultancy_id","objective_id","consultant_id","created_at","updated_at") VALUES (?,?,?) [["consultancy_id",66],["objective_id",2],["consultant_id",["created_at",2019-11-07 03:57:17 UTC],["updated_at",2019-11-07 03:57:17 UTC]]
SQL (0.1ms) INSERT INTO "teams_users" ("user_id","team_id",?) [["user_id",["team_id",311],2019-11-07 03:57:17 UTC]]
看来,团队的每个成员都有三个单独的电话。一种用于“用户负载”,一种用于“用户存在”,另一种用于“学生存在”。我还试图在调用此方法之前急于加载用户,但是我可能无法正确执行此操作。
我可以减少在这里拨打的电话吗?还有什么其他信息对我来说有用吗?
在此先感谢您的见解。