1
我有一個Event
模型與一個Service
模型如何優化此關聯鏈?
用戶可以創建一個事件,並選擇哪些服務標記到該事件many-to-many
關聯。
用戶可以訂閱服務,並且在創建事件時,如果用戶訂閱了在該事件中標記的服務,應該通知用戶。
此外,User
型號與Email
型號具有has_many
關聯。
我希望能夠獲得所有電子郵件地址的數組,因此我可以向訂閱者發送通知。
這是我有:
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
這工作,但其超強的醜惡和效率不高。我將如何去優化這個?
這裏是我的電子郵件型號:
class Email < ActiveRecord::Base
attr_accessible :address, :user_id
belongs_to :user
end
我喜歡這種方法,構建查詢在電子郵件模型上。但是我沒有關於電子郵件的用戶關聯。電子郵件在User上有一個belongs_to關聯。 – Rorshark 2013-03-08 17:04:45
具體而言,我得到這個錯誤:'ActiveRecord :: ConfigurationError:找不到名爲'users'的關聯;也許你拼錯了嗎?' – Rorshark 2013-03-08 17:05:47
可能有拼寫錯誤,我沒有你的完整模型。嘗試拆分查詢來隔離錯誤的部分。開始檢查「Email.joins(:users)」是否可以,等等...... Rails查詢指南可以幫助您查看語法。 – Baldrick 2013-03-08 17:12:43