2016-03-05 212 views
0

模型我在我的应用2种型号,UserNotification,像这样:验证触发创建关系

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]] 
... 

回答

0

在我看来,第一个问题是您加载所有用户要发送一个新的通知

iethis行每次:

users = User.where(kind: params[:kinds]) 

然后,您将更多用户添加到此对象,每次查找都会导致db调用以确定用户是否已经存在。

您应该将所有用户ID都检索到一个散列,然后添加到该散列(如果没有)。接下来,根据这个散列中的这些id发送你的通知。

+0

这是行不通的。调用'Notification.create(content:'',users:User.all)'仍然会验证每个用户。这意味着每个用户都将验证电子邮件的唯一性。问题不在于如何获取'User'模型。验证是如何被调用的 –