0
模型我在我的应用2种型号,User
和Notification
,像这样:验证触发创建关系
class Notification < ActiveRecord::Base
has_and_belongs_to_many :users
validates_presence_of :content, on: :create
end
class User < ActiveRecord::Base
has_and_belongs_to_many :notifications
validates_presence_of :email
validates_uniqueness_of :email
end
每当我要创建一个新的通知,我使用下面的代码:
这工作正常,但我看到很多数据库检查日志。这是正常的吗?有什么我可以做的,以降低数据库访问量?
日志片段:
User Load (2.1ms) SELECT DISTINCT "users".* FROM "users" WHERE "users"."kind" IN ('parent', 'student', 'teacher')
(0.1ms) begin transaction
User Exists (0.1ms) SELECT 1 AS one FROM "users" WHERE ("users"."email" = '[REDACTED]' AND "users"."id" != 34) LIMIT 1
User Exists (0.1ms) SELECT 1 AS one FROM "users" WHERE ("users"."email" = '[REDACTED]' AND "users"."id" != 36) LIMIT 1
User Exists (0.1ms) SELECT 1 AS one FROM "users" WHERE ("users"."email" = '[REDACTED]' AND "users"."id" != 38) LIMIT 1
User Exists (0.1ms) SELECT 1 AS one FROM "users" WHERE ("users"."email" = '[REDACTED]' AND "users"."id" != 40) LIMIT 1
...
SQL (0.4ms) INSERT INTO "notifications" ("content", "created_at", "updated_at") VALUES (?, ?, ?) [["content", "asdadasd"], ["created_at", "2016-03-05 13:18:27.285540"], ["updated_at", "2016-03-05 13:18:27.285540"]]
SQL (0.2ms) INSERT INTO "notifications_users" ("user_id", "notification_id") VALUES (?, ?) [["user_id", 34], ["notification_id", 843]]
SQL (0.1ms) INSERT INTO "notifications_users" ("user_id", "notification_id") VALUES (?, ?) [["user_id", 36], ["notification_id", 843]]
SQL (0.1ms) INSERT INTO "notifications_users" ("user_id", "notification_id") VALUES (?, ?) [["user_id", 38], ["notification_id", 843]]
SQL (0.1ms) INSERT INTO "notifications_users" ("user_id", "notification_id") VALUES (?, ?) [["user_id", 40], ["notification_id", 843]]
...
这是行不通的。调用'Notification.create(content:'',users:User.all)'仍然会验证每个用户。这意味着每个用户都将验证电子邮件的唯一性。问题不在于如何获取'User'模型。验证是如何被调用的 –