【问题标题】:Find using :has_many associations and multiple conditions使用 :has_many 关联和多个条件查找
【发布时间】:2014-03-03 00:14:10
【问题描述】:

在我的应用程序中,用户查看我存储在名为 View 的单独关联表中的 Pin 图。该表有一个 ID、一个 pin_id、一个 user_id 和一个排名。我想找到满足用户未见过的某些标准的 Pin 图。我正在使用 Rails 3.2.13。

这是我的模型关联:

class Pin
has_many :views
has_many :users, :through => :views

class View
belongs_to :pin
belongs_to :user

class User
has_many :pins
has_many :views  
has_many :pins, :through => :views

现在我正在这样做,它有效:

pins_controller.rb

b = TRUE
sex = current_user.sex
views = current_user.views
seen = views.map(&:pin_id)
@pins = Pin.find(:first, :conditions => ["sex = ? AND active = ? AND id not in (?)", sex, b, seen])

我认为使用连接通过单个数据库查询来拉取对象会更优雅。但是,我无法让它发挥作用。我已经阅读了一堆不同的 SO 文章,但我无法使用单个查询重现上述内容。我认为上述是环形交叉路口并且有更好的方法是正确的吗?

【问题讨论】:

    标签: mysql ruby-on-rails ruby ruby-on-rails-3


    【解决方案1】:

    您应该能够将pins 加入viewview 加入users。我认为以下内容会起作用,尽管需要viewusers 关联的具体细节:

    Pin.joins(:views => :user).where("views.sex = ? and views.active = ? and users.id not in (?)", current_user.sex, true, [current_user.id])
    

    【讨论】:

    • 其实我得到了这个错误Association named 'view' was not found; perhaps you misspelled it?
    • 已更新 - 我原本以为 Pin 只有 1 个 View。应该是:views
    • 您可以发布生成的 SQL 吗?而且,您是否也可以尝试消除 where 子句中的一些条件,看看哪个条件消除了所有记录?
    • 当我在上述查询上运行 .explain 时,我收到了这个错误:Association named 'users' was not found; perhaps you misspelled it? 我会尝试删除条件以查看问题仍然存在。
    • 黑白视图和用户的关系将决定它应该是users 还是user。是否查看belongs_tohas_many users
    【解决方案2】:

    尝试 squeel 它比普通的主动记录查询方法更伤人更胜一筹,并为您提供更强大的功能

    https://github.com/activerecord-hackery/squeel

    http://railscasts.com/episodes/354-squeel

    【讨论】:

    • 针对 squeel 与仅链接的问题提出解决方案。这对提出问题的人会更有帮助。
    【解决方案3】:

    你可以这样做:

    Pin.joins(:views).where(sex: sex, active: b).
      merge(View.where(View.arel_table[:user_id].not_eq(current_user.id))).first
    

    【讨论】:

    • 这也将@pins 返回为零。
    • 我刚刚在自己的代码中遇到了类似的问题,所以我改变了我目前如何实现它的答案,希望它对你有用
    • 刚刚意识到这个答案没有考虑没有视图的 Pin 图,所以可能没那么有用
    猜你喜欢
    • 2023-03-04
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多