Rails has_many through - 通过介入模型属性获取值

时间:2012-08-03 03:35:14

标签: ruby-on-rails has-many-through

我有三个模型,有很多通过关联,基本上通过会员资格将用户连接到帐户:

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.ownerAccount.first.adminsAccount.first.executives方法。显然,事实上,我只是获得会员资格。

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

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

1 个答案:

答案 0 :(得分: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.owneraccount.admins即可使用此代码。