【问题标题】::through relations in rails: query by attribute in related table:通过rails中的关系:通过相关表中的属性查询
【发布时间】:2009-01-27 18:45:49
【问题描述】:

我有以下 Rails 定义:

Class Book
  string title
  has_many readings
  has_many users, :through => :readings

Class Reader
  int rating
  belongs_to :book
  belongs_to :user

Class User
  has_many readings
  has_many books, through => :readings

不,我想这样查询:

给我所有具有 book.title = "test" 的用户 A 的阅读评分

你能帮帮我吗?谢谢!

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    这将为您提供一本书的所有评分的数组 标题为“test”,由名为“A”的用户阅读

    User.find_by_name("A").books.find_by_title("test").readings.map{|r| r.rating }
    

    但说实话,我真的不确定这是否是你想要的。

    【讨论】:

      【解决方案2】:

      您可以包含相关模型并将其用作参数。

      Users.find(
        :all,
        :include => {:readings => :books},
        :conditions => "books.title = ? AND etc"
      )
      

      显然不是 100% 正确,但应该会给你正确的想法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-18
        相关资源
        最近更新 更多