3

I am new to rails. What is the equivalent rails query for the following sql query?

mysql> select a.code, b.name, b.price, b.page from article a inner join books b on a.id =b.article_id;

I am trying

Article.joins(:books).select("books.name, books.price, books.page, articles.code")

The active record relation returns only table one data

 => #<ActiveRecord::Relation [#<Article id: 1, code: "x", created_at: "2014-11-12 13:28:08", updated_at: "2014-11-14 04:16:06">, #<Article id: 2, code: "y", created_at: "2014-11-12 13:28:08", updated_at: "2014-11-14 04:00:16">]> 

What is the solution to join both table?

1 Answer 1

1

You normally don't really query like that directly with Rails. Instead, you'd set up your models and use other associated models to achieve this. If speed is an issue, you can use eager loading. If you absolutely need exactly this join, it's:

class Article < ActiveRecord::Base
  has_many :books
  scope :with_books, lambda { 
    joins(:books)
      .select('articles.code, books.name, books.price, books.page') 
  }
end 

class Book < ActiveRecord::Base
  belongs_to :article
end

But this is not so useful. It generates the join you want, but retrieving the book details like that won't be fun. You could do something like:

a = Article.with_books.where("books.name = 'Woken Furies'").first
a.code

And that should give you the article code. Depending on what you need, a better way could be to remove the scope from the Article class and instead query like:

b = Book.where(name: 'Woken Furies')
      .joins(:article)
      .where("articles.code = 'something'")

b = Book.where("name = 'Woken Furies' AND articles.code = 'something'")
      .joins(:article)

Both of these queries should be equivalent. You can get from one associated record to the other with:

book = b.first
article_code = book.article.code

I'm not sure what you need to accomplish with the join, but I think you might get more beautiful code by using plain ActiveRecord. If you need the speed gain, avoid n+1 problems, etc., it might make sense to write those joins out by hand.

I hope I understood your question correctly.

There's more about joining in the Rails guides:

http://guides.rubyonrails.org/active_record_querying.html#joining-tables

Update: You can use pluck if you need to retrieve e.g. just the code and the name:

Article.with_books
  .where("books.name = 'Woken Furies'")
  .pluck('articles.code, books.name')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.