繁体   English   中英

关联,联接和范围

[英]Associations, Joins and Scopes

我有以下设置:

class Program
   has_many :participants
end

class Participant
   belongs_to :user
end

class User
   has_many :participants
end

我希望类方法或范围返回特定用户参与的所有程序。 这是我到目前为止所拥有的:

def self.where_user_participates(user)
   Program.joins(:participants).where('participants.user_id' => user.id)
end

我相信这有效,但我并不喜欢它。 我不想谈论'id'但是使用关联,但我无法让它工作,例如:

def self.where_user_participates(user)
  Program.joins(:participants).where('participants.user' => user)
end

我怎样才能改善这个? 是否真的不需要官方的“范围”,并且类方法是Rails 3中的“最佳实践”?

class Program
  has_many :participants
end

class Participant
  belongs_to :user
  belongs_to :program
end

class User
  has_many :participants
  has_many :programs, :through => :participants
end

然后打电话给程序:

user.programs

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM