views:

117

answers:

2

Hello,

I'm new to rails and building a small test app on rails3 (beta4).

I am using Authlogic to manage user sessions (setup in a standard fashion as per this tutorial)

I have scaffolded and setup a card model (a post basically), and set up the basic active record associations for a belongs_to and has_many relationship

user.rb

has_many :cards

card.rb

belongs_to :user

I added my foreign key column to my cards table: user_id which defaults to 1

Everything works fantastically. I've done my views and I can see the associations, card can belong to various users and it's all great.

But I can not seem to grab the current active user when creating a new card

cards_controller.rb

def new
  @card = Card.new
  @card.user = current_user

  respond_to do |format|
    format.html # new.html.erb
    format.xml  { render :xml => @card }
  end
end

current_user is defined in the application controller, available to view here

user_id is passing NULL and nothing gets written to the database user_id column, leaving it to default to 1 rather than the ID of actual signed in user.

I tried the obvious things like @user = current_user

It's probably something super simple, but today is my first real day with rails - Thanks!

+3  A: 

Right now, it appears as you are setting the user on the new action, but not on the create action.

I see 2 options, the latter being the better:

  1. If you continue to leave @card.user = current_user in your new action you can set a hidden input field card[user_id] which can contain the current user's id. This is a totally bad idea because anyone can just throw whatever they want into that field.

  2. Try moving @card.user = current_user right before your @card.save line in the create action. This way the user can't mess around with it, and it will set it to your card object when it's actually about to be saved.

theIV
Perfect, it's so obvious! Being new to the framework I wasn't even considering the fact that the new action doesn't actually save the card :) Thanks!
Alex
I think we've all 'been there, done that.' :)
theIV
+1  A: 

A common Rails idiom (in RESTful controllers) is to create an instance of your Card (@card) in the new action, render a view to the browser, then save this object to the database in the create action (assuming you have some intermediate capture of additional card details from the user in between these actions). You can use Rails associations to correctly build the card instance with the correct user. Rails 3 introduced a streamlined responder facility as shown here also.

respond_to :html, :xml

def new
  respond_with(@card = current_user.cards.build)
end

def create
  @card = current_user.cards.new(params[:card])
  if @card.save
    respond_with(@card)
  else
    // Do something else to handle the error case....
  end
end
bjg