Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Assuming you have associations in your models, you can simply do as follow</p> <pre><code>User.joins(:tasks).select('users.user_id, tasks.task_id') </code></pre> <p>you can also do as follow</p> <pre><code>User.includes(:tasks).where("user.id =tasks.user_id") </code></pre> <p>includes will do eager loading check the example below or read eager loading at <a href="http://guides.rubyonrails.org/active_record_querying.html" rel="nofollow">here</a></p> <pre><code>users = User.limit(10) users.each do |user| puts user.address.postcode end </code></pre> <p>This will run 11 queries, it is called N+1 query problem(first you query to get all the rows then you query on each row again to do something). with includes Active Record ensures that all of the specified associations are loaded using the minimum possible number of queries.</p> <p>Now when you do;</p> <pre><code>users = User.includes(:address).limit(10) user.each do |user| puts user.address.postcode end </code></pre> <p>It will generate just 2 queries as follow</p> <pre><code>SELECT * FROM users LIMIT 10 SELECT addresses.* FROM addresses WHERE (addresses.user_id IN (1,2,3,4,5,6,7,8,9,10)) </code></pre> <p>Plus if you don't have associations then read below;</p> <p>you should be have to look at <a href="http://guides.rubyonrails.org/association_basics.html" rel="nofollow">http://guides.rubyonrails.org/association_basics.html</a> Assuming your are trying to do inner join, by default in rails when we associate two models and then query on them then we are doing inner join on those tables.</p> <p>You have to create associations between the models example is given below</p> <pre><code>class User has_many :reservations ...# your code end </code></pre> <p>And in reservations</p> <pre><code>class Reservations belongs_to :user ... #your code end </code></pre> <p>Now when you do</p> <pre><code>User.joins(:reservations) </code></pre> <p>the generated query would look like as follow</p> <pre><code>"SELECT `users`.* FROM `users` INNER JOIN `reservations` ON `reservations`.`user_id` = `users`.`id`" </code></pre> <p>you can check the query by doing <code>User.joins(:reservations).to_sql</code> in terminal</p> <p>Hopefully it would answer your question</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload