Has_many通过作用域条件



我是Rails新手,有一个关于在has_many :through关系上添加条件的问题。我想在FacebookUser模型中有一个:joined_groups关系。joined_groups将是满足where(accepted: true)条件的GroupInvite表。然而,我不知道如何用Rails实现这一点,或者这是否是正确的方法。我有以下型号…

Group.rb

class Group < ActiveRecord::Base
  attr_accessible :description, :name
  ...
  #Relationships
  has_many :group_invites, class_name: 'GroupInvite'
  has_many :facebook_users, class_name: 'FacebookUser', :through => :group_invites, :source => :facebook_user
end

GroupInvite.rb

class GroupInvite < ActiveRecord::Base
  attr_accessible :accepted, :facebook_user_uid, :group_id, :admin
  ...    
  #Relationships
  belongs_to :group
  belongs_to :facebook_user, :foreign_key => :facebook_user_uid, :primary_key => :facebook_user_uid
  #Scopes
  scope :pending, where(accepted: nil)
  scope :declined, where(accepted: false)
  scope :joined, where(accepted: true)
end

FacebookUser

class FacebookUser < ActiveRecord::Base
  #Attributes
  attr_accessible :first_name, :gender, :last_name, :uid
  ...
  has_many :group_invites, class_name: 'GroupInvite', :primary_key => :uid, :foreign_key => :facebook_user_uid
  has_many :groups, class_name: 'Group', :through => :group_invites, :source => :group
  ...
end

任何帮助都将非常感激!

你可以试试这个吗:

has_many :accepted_group_invites, class_name: 'GroupInvite', :primary_key => :uid, :foreign_key => :facebook_user_uid, :conditions => { :accepted => true }

马特

最新更新