I have a problem in the rails. Im actually solving this, but I guess theres an easier way there.
I got user models / members / groups and user models / invitations / events. Membership joins the user and the group. The invitation joins the user and the event.
The membership and invitation model is the same. A group and an event have several identical columns. The membership / invitation model has a logical โacceptedโ column, that is, the user invited to the group / event must accept this invitation before he becomes a participant / participant.
Now, if the user subscribes in all groups, invitations should appear in the list. In fact, I want to add even more notifications to the system, and the events are not yet included in mine.
My solution is to add a notification model owned by the user. Therefore, each user has many notifications. In addition, this model is polymorphic and refers to 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
I added some data to the database, and Im tested them on the console
myUser = User.find(6)
I will run all notifications with each of them ... but first I check all further actions with one notification
myNotice = myUser.notifications.first
whether visible_type of myNotices is a membership or an invitation, I will show it as a notification about a group or event in this case noticeable_type = membership
myGroup = Group.find(Membership.find(myNotice.noticeable_id).group_id)
-> Do you want to join the group "myGroup.name"? Yes | No
On Yes: Membership.find(myNotice.noticeable_id).accepted = true
On No: Membership.find(myNotice.noticeable_id).destroy
And: myNotice.destroy
This is my idea. Is this a way to solve the problem?
"Each of them," which goes through all the notifications, will be in the view file. This means that "Group.find (Membership.find (myNotice.noticeable_id) .group_id)" must be in the views file or partially. Isn't that ugly?
I think I used a lot of โfindsโ, which means a lot of SQL queries. Isn't there a way to reduce them with some kind of "Ruby on Rails" -magic?
Thanks:)