我是Rails的新手,并且对于has_many :through
关系的条件有疑问。我想在:joined_groups
模型中建立FacebookUser
关系。 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
非常感谢任何帮助!
答案 0 :(得分:0)
你可以试试这个:
has_many :accepted_group_invites, class_name: 'GroupInvite', :primary_key => :uid, :foreign_key => :facebook_user_uid, :conditions => { :accepted => true }
Matta的