1

我在一个有多个通过关联的三个模型中,基本上通过会员资格将用户连接到帐户,如下所示:

class User < ActiveRecord::Base

  attr_accessible :email, :password, :password_confirmation, :remember_me

  has_many :memberships
  has_many :accounts, :through => :memberships    
end

class Account < ActiveRecord::Base
  attr_accessible :expiration_date, :name, :status, :url

  has_many :memberships
  has_many :users, :through => :memberships

  has_one  :owner, :class_name => "Membership", :conditions => ["role = ?", "Owner"]
  has_many :admins, :class_name => "Membership", :conditions => ["role = ?", "Admin"]
  has_many :executives, :class_name => "Membership", :conditions => ["role = ? OR role = ?", "Owner", "Admin"]

end

class Membership < ActiveRecord::Base
  attr_accessible :account_id, :user_id, :role

  validates :role, :uniqueness => { :scope => :account_id }, :if => "role == 'Owner'"

  belongs_to :account
  belongs_to :user
end

我希望能够通过这些方法Account.first.owner和. 显然,事实上,我只是获得会员资格。Account.first.adminsAccount.first.executives

我可以通过在我的帐户模型上定义新方法来轻松实现这一点,使用类似self.memberships.find_by_role('Owner').userand self.memberships.find_all_by_role("Admin").collect {|u| u.user},但对我来说似乎更草率。有没有办法纯粹通过关联来做到这一点?

非常感谢任何帮助,包括批评我的方法......谢谢!

4

1 回答 1

0

在 Rails 3 中,您可以通过定义自己的方法来真正有效地完成这类事情。例如:

class Account < ActiveRecord::Base
  has_many :memberships
  has_many :users, :through => memberships

  def owner
    users.where(:role => 'Owner').first
  end

  def admins
    users.where(:role => 'Admin')
  end
end

account.owner只需调用或即可使用此代码account.admins

于 2012-08-03T05:40:03.720 回答