所有列都在rails上的ruby中加入

时间:2015-02-03 20:46:30

标签: sql ruby-on-rails join

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

我该怎么办?

3 个答案:

答案 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