I have an Event
model with a many-to-many
association with a Service
model
我有一个与服务模型具有多对多关联的事件模型
A user can create an event and choose what services are tagged to that event.
用户可以创建事件并选择标记到该事件的服务。
A user can subscribe to a service, and when an event gets created the user should be notified if the user has subscribed to a service that was tagged in that event.
用户可以订阅服务,并且当创建事件时,如果用户订阅了在该事件中标记的服务,则应该通知用户。
In addition, the User
model has a has_many
association to an Email
model.
此外,User模型与Email模型具有has_many关联。
I'd like to be able to get an array of all the email addresses so I can send a notification to the subscribers.
我希望能够获得所有电子邮件地址的数组,以便我可以向订阅者发送通知。
Here's what I have:
这就是我所拥有的:
class Event < ActiveRecord::Base
has_many :event_services, :dependent => :destroy
has_many :services, :through => :event_services
def recipients
recipients = services.each_with_object(arr = []) do |service|
service.users.each do |user|
user.emails.each do |email|
arr << email.address
end
end
end
end
recipients.uniq
end
This works, but its super ugly and not very efficient. How would I go about optimizing this?
这是有效的,但它超级丑陋,效率不高。我该如何优化这个?
Here's my Email model:
这是我的电子邮件模型:
class Email < ActiveRecord::Base
attr_accessible :address, :user_id
belongs_to :user
end
1 个解决方案
#1
3
It would be more efficient with a single SQL request The following request, using multiple joins, should work:
使用单个SQL请求会更有效使用多个连接的以下请求应该有效:
def recipients
Email.joins(:user => {:services => :event_services}).where(:event_services => {:event_id => self.id}).pluck(:address).uniq
end
#1
3
It would be more efficient with a single SQL request The following request, using multiple joins, should work:
使用单个SQL请求会更有效使用多个连接的以下请求应该有效:
def recipients
Email.joins(:user => {:services => :event_services}).where(:event_services => {:event_id => self.id}).pluck(:address).uniq
end