Home Rails: Loop thru two different models
Reply: 0

Rails: Loop thru two different models

user1168
1#
user1168 Published in July 19, 2018, 3:11 pm

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?

You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO