views:

39

answers:

2

I have two Models called User and Membership. User has_many :memberships Membership belongs_to :user

What is the proper way to modify MembershipsController's index method to set @memberships to all the memberships there are for the user "session[:user_id]"?

I tried something like: @memberships = Membership.find(:all, :conditions => ["user_id = ?", session[:user_id]] )

but then Rails is Selecting from users instead of memberships:

Rendering memberships/index
  ←[4;35;1mUser Columns (3.0ms)←[0m   ←[0mSHOW FIELDS FROM `users`←[0m
  ←[4;36;1mUser Load (1.0ms)←[0m   ←[0;1mSELECT * FROM `users` WHERE (`users`.`id` = 1) LIMIT
  ←[4;35;1mCACHE (0.0ms)←[0m   ←[0mSELECT * FROM `users` WHERE (`users`.`id` = 1) LIMIT 1←[0m
A: 

user_id wasn't being set correctly.

script/console:

>> Membership.find(:first, :conditions => "user_id = 1")
=> nil

Logs:

Completed in 19ms (View: 9, DB: 6) | 200 OK [http://localhost/memberships]
  [4;36;1mSQL (0.0ms)[0m   [0;1mSET NAMES 'utf8'[0m
  [4;35;1mSQL (0.0ms)[0m   [0mSET SQL_AUTO_IS_NULL=0[0m
  [4;36;1mUser Columns (2.0ms)[0m   [0;1mSHOW FIELDS FROM `users`[0m
  [4;35;1mSQL (0.0ms)[0m   [0mSHOW TABLES[0m
  [4;36;1mUser Load (0.0ms)[0m   [0;1mSELECT * FROM `users` WHERE (`users`.`id` = 1) [0m
  [4;35;1mMembership Load (1.0ms)[0m   [0mSELECT * FROM `memberships` WHERE (user_id = 1) LIMIT 1[0m
  [4;36;1mMembership Load (0.0ms)[0m   [0;1mSELECT * FROM `memberships` WHERE (user_id = 1) LIMIT 1[0m
Tie-fighter
A: 

What does session[:user_id] represent? Are you trying to roll your own authentication system?

There are a number of authentication solutions that can handle the ins and outs of that for you.

To answer your question though, you probably want to be making use of the associations you've set up between the two models:

def index
  @user = User.find(session[:user_id])
  @memberships = @user.memberships if @user
end

Using an application-wide authentication system (whether of your own-making or using a library) this would most likely be simplified to:

def index
  @memberships = current_user.memberships
end

where current_user is a method defined in ApplicationController that returns the currently logged in user and the index action has a before_filter that ensures that the user is logged in.

fractious