有很多通过与条件的关联
我正在尝试通过关联向 a has many 添加一个条件,但没有运气.这是我的视频模型中的关联:
I am trying to add a condition to a has many through association without luck. This is the association in my video model:
has_many :voted_users, :through => :video_votes, :source => :user
我只想获取视频投票的 value
等于 1 的 voted_users
.我该怎么做?
I want to only get the voted_users
whose video_votes have a value
equal to 1 for that video. How would I do this?
我会分 2 个阶段进行:
I'd do this in 2 stages:
首先,我将在没有任何条件的情况下定义模型之间的 has_many :through
关系.
First, I'd define the has_many :through
relationship between the models without any conditions.
其次,我会添加一个定义 where 条件的范围".
Second, I'd add a 'scope' that defines a where condition.
具体来说,我会这样做:
Specifically, I'd do something like:
class User < ActiveRecord::Base
has_many :video_votes
has_many :votes, :through=>:video_votes
def self.voted_users
self.video_votes.voted
end
end
class VideoVote
def self.voted
where("value = ?", 1)
end
end
class Video
has_many :video_votes
has_many :users, :through=>:video_votes
end
然后您可以使用以下方法获取已投票的用户:
Then you could get the users that have voted using:
VideoVote.voted.collect(&:user).uniq
我相信这会返回所有投票用户的数组.这不是您要使用的确切代码——它们只是片段——但想法是一样的.
which I believe would return an array of all users who had voted. This isn't the exact code you'd use -- they're just snippets -- but the idea is the same.