activerecord - Rails - get results of many to many query without nested loops -


i'm new rails , trying figure out better way outputted data query on many many relationship.

here models:

   class user < activerecord::base       has_many :takes       has_many :tests, through: :takes        has_many :provides       has_many :tests, through: :provides     end      class test < activerecord::base       has_many :takes       has_many :users, through: :takes        has_many :provides       has_many :users, through: :provides     end      class provide < activerecord::base         belongs_to :user         belongs_to :test     end      class take < activerecord::base         belongs_to :user         belongs_to :test     end 

here query:

@test = test.includes(:users).where("id = ?", 1) 

and here how i'm working data, need able each row test.* data, user.* data, , provide.id. provide.id problem - can't seem it.

    <% @test.each |t| %>         <% t.users.each |u| %>             <tr>                 <td><%= u.display_name %></td>                 <td><%= link_to g.name, waiting_area_path(t.id, u.id) %></td>                 <td><%= t.description %></td>                 <td><%= u.city + " - " + u.add_l1 %></td>             </tr>         <% end %> 

when try access provide table data doing t.provides.each can loop through of fields, need grab provide.id row i'm getting test.id , user.id.

for example, try add line this, error saying method doesn't exist.

<% @test.each |t| %>     <% t.users.each |u| %>         <tr>             <%= u.username +"|"+ t.provides.where('user_id ='+u.id)%>             <td><%= link_to g.name, waiting_area_path(t.id, u.id) %></td>             <td><%= t.description %></td>             <td><%= u.city + " - " + u.add_l1 %></td>         </tr>     <% end %> 

how can data? these active record objects getting pain work with...

you need differentiate between take test , provide test, same user take , user provide. change associations to

class user < activerecord::base   has_many :takes   has_many :take_tests, through: :takes    has_many :provides   has_many :provide_tests, through: :provides end  class test < activerecord::base   has_many :takes   has_many :take_users, through: :takes    has_many :provides   has_many :provide_users, through: :provides end 

then use following code go through list of users test.

@tests = test.includes(provides: :user).where(tests: { id: 1 })  <% @tests.each |test| %>   <% test.provides.each |provide| %>     <tr>       <td><%= link_to g.name, waiting_area_path(test, provide.user) %></td>       <td><%= test.description %></td>       <td><%= "#{provide.user.city} - #{provide.user.add_l1}" %></td>     </tr>   <% end %> <% end %> 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -