Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreign key (class_id) not populating in belongs_to association

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!

like image 721
Alex Avatar asked Jan 21 '23 20:01

Alex


1 Answers

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.

like image 102
theIV Avatar answered Jan 31 '23 08:01

theIV