如何在rails类模型范围中使用'SELECT ... FROM ... WHERE ... IN(SELECT ...)'格式编写SQL?

时间:2018-06-18 05:42:24

标签: sql ruby-on-rails ruby activerecord

如何使用

编写SQL
SELECT * 
FROM tableA 
WHERE tableA.col1 IN (
  SELECT tableB.col2 
  FROM tableB
)

在Rails模型范围内?

目前,我在ruby模型文件中有一个这样的SQL作为类方法:

class Book
  def self.select_list_for_current_project_fund_schemes_sponsor_name
    Books.connection.select_all('
      SELECT book.name, book.name 
      FROM BOOK b
      WHERE b.b_pk IN (
        SELECT s.b_fk
        FROM STORE s
      )
    ').rows
  end
end

它可以工作,并产生我想要的输出:

Book.select_list_for_current_project_fund_schemes_sponsor_name
=> [[book_name1, book_name1], [book_name2, book_name2], [book_name3, book_name3]...]

但是我想在范围内写它,所以它与其他代码一致。

如何使用ActiveRecord'where class in class model scope?

编写上面的SQL

我想在类的模型文件中输入类似的内容:

class Book
  scope :books_in_store_that_exist, -> { where(magic_sql_wrapped_in_ruby_here) }

  # more code here...
end

注意:我没有Store的模型,我只有Book模型。

换句话说,我希望能够通过编写

来实现相同的输出
Book.books_in_store_that_exist.select(:name).map {|b| [b.name, b.name]}
=> [[book_name1, book_name1], [book_name2, book_name2], [book_name3, book_name3]...]

1 个答案:

答案 0 :(得分:1)

在这种情况下,您只需要添加内连接

class Book
  scope :books_in_store_that_exist, -> { joins("INNER JOIN stores ON books.b_pk = stores.b_fk") }
end

现在你可以用它来链接它。

Book.books_in_store_that_exist.select(:name).map { |b| [b.name, b.name] }
#=> [[book_name1, book_name1], [book_name2, book_name2], [book_name3, book_name3]...]