有很多通过与条件的关联 [英] Has many through associations with conditions

查看:47
本文介绍了有很多通过与条件的关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过关联向 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.

这篇关于有很多通过与条件的关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆