我有三个模型,有很多通过关联,基本上通过会员资格将用户连接到帐户:
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.admins
和Account.first.executives
方法。显然,事实上,我只是获得会员资格。
我可以通过使用self.memberships.find_by_role('Owner').user
和self.memberships.find_all_by_role("Admin").collect {|u| u.user}
之类的内容在我的帐户模型上定义新方法来轻松实现这一目标,但对我来说似乎更为草率。有没有办法纯粹通过协会来做到这一点?
非常感谢任何帮助,包括批评我的方法......谢谢!
答案 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.owner
或account.admins
即可使用此代码。