class Person
has_many :owned_groups, :class_name => "Group", :foreign_key => :owner_id
has_many :owned_group_memberships, :through => :owned_groups,
:source => :group_memberships
has_many :group_memberships, :foreign_key => "member_id"
has_many :groups, :through => :group_memberships
end
class GroupMembership
belongs_to :member, :class_name => 'Person'
belongs_to :group
end
class Group
belongs_to :owner, :class_name => "Person"
has_many :group_memberships
has_many :members, :through => :group_memberships
end
我想创建模型Message
,以便Person
可以在group#show
页面中发布新消息。但是,为此,她/他必须来自有问题的Group
或所有者,或者拥有该组中的group_membership(成为会员)。
模型Message
的关联怎么样?
答案 0 :(得分:2)
class Message < ActiveRecord::Base
belongs_to :person
belongs_to :group
validate :has_group_permission
def has_group_permission
unless self.person.owned_groups.include?(self.group) || self.person.groups.include?(self.group)
self.errors.add(:base, "you don't have permission to add a message to this group."
end
end
end