class Category < ActiveRecord::Base
has_many :articles
end
class Article < ActiveRecord::Base
belongs_to :category
has_many :comments
has_many :tags
end
导轨中的 Category.joins(:articles)
等效
SELECT categories.* FROM categories
INNER JOIN articles ON articles.category_id = categories.id
如果我想拥有rails-code,则等效于sql
SELECT * FROM categories
INNER JOIN articles ON articles.category_id = categories.id
我该怎么办?
答案 0 :(得分:2)
Category.select('*').joins(:articles)
或
categoyes = Category.select('*').includes(:articles)
和
categoyes.each do |category|
puts category.articles
end
答案 1 :(得分:0)
尝试使用select
方法
categories = Category.select('*').joins(:articles)
categories.first.some_column_from_articles
答案 2 :(得分:0)
我使用这种方法
Category.connection.select_all("SELECT * FROM categories
INNER JOIN articles ON articles.category_id = categories.id").to_a