Rails find over multiple models
- by kgb
I think I'm missing something very obvious and its making my brain hurt.
class User < ActiveRecord::Base
has_one :profile
class Profile < ActiveRecord::Base
has_one :user
belongs_to :team
I have a partial that loops through the users and print some basic info, I'm using this partial in my team show page.
I had originally written this to return users who's profiles were a member of a team.
def show
@team = Team.find_by_id(params[:id])
@profiles= Profile.find(:all, :conditions => ['team_id = ?', @team.id])
@users = User.find_by_id(@profiles.user_id)
end
But quickly realized @profiles was an array, and it looks messy as hell. Stuck as to what my find should look like to select all User who have a profile that is a member of a team.
The partial that is working elsewhere for displaying users looks like this
<% for user in @users%>
<table>
<tr>
<td>
<%= image_tag user.profile.picture.url %>
</td>
<td>
<a href="/users/<%= user.id %>"><%= user.login %></a>
</td>
<td>
<%= user.profile.first_name %> <%= user.profile.second_name %>
</td>
<td>
<%= user.profile.status %>
</td>
</tr>
</table>
<% end %>
Development log output with updated show and relationships
Processing TeamsController#show (for 127.0.0.1 at 2010-03-30 22:06:31) [GET]
Parameters: {"id"=>"1"}
User Load (1.3ms) SELECT * FROM "users" WHERE ("users"."id" = 3) LIMIT 1
Team Load (1.0ms) SELECT * FROM "teams" WHERE ("teams"."id" = 1)
Rendering template within layouts/main
Rendering teams/show
Completed in 75ms (View: 11, DB: 2) | 200 OK [http://localhost/teams/1]