我在 Rails 中遇到了问题。我实际上正在解决它,但我想还有更简单的方法。
我得到了用户/成员(member)/组模型和用户/邀请/事件模型。成员资格加入用户和组。邀请加入用户和事件。
成员(member)和邀请模式是平等的。组和事件确实有一些相同的一些不同的列。成员(member)/邀请模型都有一个 bool 列“已接受”,这意味着受邀加入群组/事件的用户在成为成员(member)/参与者之前必须接受此邀请。
现在,如果用户登录所有群组,事件邀请应该出现在列表中。事实上,我想稍后向系统添加更多通知,而事件甚至还没有包含在我的系统中。
我的解决方案是添加一个属于用户的通知模型。所以每个用户都有很多通知。另外,这个模型是多态的,属于membership AND invitation。
#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
我向数据库添加了一些数据并在控制台中对其进行了测试
myUser = User.find(6) # will be exchanged with current_user in the actual program
我将在每个通知中运行所有通知...但一开始我会在一个通知上测试所有进一步的操作
myNotice = myUser.notifications.first
因此无论 myNotices 的 noticeable_type 是成员(member)还是邀请,我都会将其呈现为群组或事件通知 在这种情况下 noticeable_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
这就是我的想法。 这是解决问题的方法吗?
遍历所有通知的“每做”将在 View 文件中。这意味着“Group.find(Membership.find(myNotice.noticeable_id).group_id)”必须位于 View 文件或部分 View 文件中。是不是有点丑?
我认为我使用了很多“查找”,这意味着很多 SQL 查询。有没有办法用任何“Ruby on Rails”魔术来减少它们?
谢谢你:)
最佳答案
我的应用程序需要类似的东西,所以在这里更新答案以防有人发现它有用。
#user model
has_many :membership_notices, :through => :notifications, :source => :membership, :conditions => {"notifications.noticeable_type" => "membership"}
has_many :event_notices, :through => :notifications, :source => :event ,:conditions => {"notifications.noticeable_type" => "event"}
通知现在可以访问为
user.membership_notices
user.event_notices
关于ruby-on-rails - Rails - 如何在某些事件上给用户通知消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14007172/