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!
Right now, it appears as you are setting the user on the
newaction, but not on thecreateaction.I see 2 options, the latter being the better:
If you continue to leave
@card.user = current_userin yournewaction you can set a hidden input fieldcard[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.Try moving
@card.user = current_userright before your@card.saveline in thecreateaction. 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.