Im在rails中有問題。我實際上解決它,但我想這是一個更簡單的方法。Rails - 如何在某些事件上給用戶通知消息
我得到了用戶/會員/組模型和用戶/邀請/事件模型。成員加入用戶和組。邀請加入用戶和事件。
成員資格和邀請模式相同。組和事件確實有一些相同的一些不同的列。會員/邀請模式都有一個布爾列「已接受」,這意味着被邀請參加團體/活動的用戶必須在他是成員/參與者之前接受此邀請。
現在如果用戶登錄所有組並且事件邀請應出現在列表中。事實上,我想在稍後添加更多的通知給系統,事件甚至還沒有包含在我的系統中。
我的解決方案是添加屬於用戶的通知模型。所以每個用戶都有很多通知。此外,這種模式是多態的,屬於會員和邀請。
#user model
class User < ActiveRecord::Base
has_many :memberships, :dependent => :destroy
has_many :groups, :through => :memberships
has_many :invitations, :dependent => :destroy
has_many :events, :through => invitations
has_many :notifications
#membership model (equal to invitation model)
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :group
has_one :notifications, :as => :noticeable
#group model (equal to event model but participants for members and invitation for membership)
class Group < ActiveRecord::Base
has_many :memberships
has_many :users, :through => :memberships
has_many :members, :through => :memberships, :source => :user,
:conditions => ['memberships.accepted = ?', true]
#notification model
class Notification < ActiveRecord::Base
belongs_to :user
belongs_to :noticeable, :polymorphic => true
香港專業教育學院增加了一些數據到數據庫和Im測試它在控制檯
myUser = User.find(6) # will be exchanged with current_user in the actual program
我將通過與各所有通知運行做......但一開始我測試所有進一步的行動上一個通知
myNotice = myUser.notifications.first
所以無論myNotices的noticeable_type是會員或邀請,我將使它在這種情況下,通知組或事件通知 able_type = membership
myGroup = Group.find(Membership.find(myNotice.noticeable_id).group_id)
- >你想加入集團「myGroup.name」嗎?是|沒有
開啓是:Membership.find(myNotice.noticeable_id).accepted = true
在編號:Membership.find(myNotice.noticeable_id).destroy
兼:myNotice.destroy
這就是我的想法。 這是解決問題的方法嗎?
通過所有通知的「每個做」將在一個視圖文件中。這意味着「Group.find(Membership.find(myNotice.noticeable_id).group_id)」必須位於視圖文件或部分視圖中。這難道不是很難看嗎?
我認爲我使用了很多「查找」,這意味着許多SQL查詢。難道沒有辦法用任何「Ruby on Rails」來降低它們嗎?
謝謝:)
你可以嘗試使用.includes或.joins與關聯模型的加入。 – Nich