Rails - 创建新模型所需的帮助

时间:2011-05-23 02:27:53

标签: ruby-on-rails ruby-on-rails-3 associations models

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的关联怎么样?

1 个答案:

答案 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