Theopap
Theopap

Reputation: 755

Rails: Loop thru two different models

I have implemented a basic search and I'm looping thru the results like this:

views/items/search.html.erb

 <% if @items.present? %>
       <% if @items %>
         <% @items.each do |item| %>
             <%= link_to item.title, item %>
               <%= number_to_currency item.price %>
           <% end %>
         <% end %>
    <% end %> 

Also I have an account.rb which belongs_to :user and contains all the details regarding address, phone# etc.

Model associations:

class Account < ApplicationRecord
  belongs_to :user
end

class Item < ApplicationRecord
  belongs_to :user
  belongs_to :account
end

class User < ApplicationRecord
  has_one :account, autosave: true
  has_many :items
end

Also, I have t.integer "user_id" under accounts and items tables as well.

I would like to show the account information of the specific item on the results. How can I loop thru two different models and show the desired result?

Upvotes: 1

Views: 56

Answers (1)

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33491

You can use joins passing the association between Account and User, and the association with User and Item, like:

Account.joins(user: :items).where(items: { id: item_id })

This would give you a SQL query asking for each column in the Account table joining the users.id with accounts.user_id and items.user_id with users.id, asking for each Item record with id equal to item_id:

SELECT "accounts".*
FROM "accounts"
INNER JOIN "users"
ON "users"."id" = "accounts"."user_id"
INNER JOIN "items"
ON "items"."user_id" = "users"."id"
WHERE "items"."id" = ?  [["id", item_id]]

Upvotes: 2

Related Questions