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 new
action, but not on the create
action.
I see 2 options, the latter being the better:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With