Home Rails: Loop thru two different models
Reply: 1

Rails: Loop thru two different models

Theopap
1#
Theopap Published in 2017-11-10 10:53:10Z

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?

Sebastian Palma
2#
Sebastian Palma Reply to 2017-11-10 11:05:28Z

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]]
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.315277 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO