Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use inner join in Ruby On Rails

I am working on rails.

my need is,

@accountUrl = Account.find_by_id(current_account_id)

@details = Detail.find_by_acc_id(@accountUrl.id)

How to write inner join query from above example

Can any one.

like image 985
suresh.g Avatar asked Oct 03 '12 05:10

suresh.g


People also ask

What is join in Ruby on Rails?

Ruby on Rails ActiveRecord Query Interface Joins joins() allows you to join tables to your current model.

What is ActiveRecord in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


2 Answers

In this simple case Rails does not use a join, it joins "in code":

Account.includes(:details).where(:id => current_account_id).first

It will make two separate queries.

If you need a condition for the select, you have to join "by hand" (or through a scope)

Account.joins(:details).where("details.name" => selected_detail).first

This will make an INNER JOIN and return only accounts satistfying the conditions.

like image 192
rewritten Avatar answered Oct 18 '22 18:10

rewritten


model A
  has_many :bs

model B
  has_many :cs

in model A, u can write

has_many :cs, :through => :bs #uses inner join to fetch the records.

check out http://guides.rubyonrails.org/active_record_querying.html and http://asciicasts.com/episodes/215-advanced-queries-in-rails-3

like image 40
prasad.surase Avatar answered Oct 18 '22 19:10

prasad.surase