Anytime I create a user and log in this exception is thrown on the redirect: Couldn't find User without an ID.
I have a has_many association like so:
class Post < ActiveRecord::Base
has_many :tags
belongs_to :user
attr_accessible :title, :description, :content, :tags_attributes
accepts_nested_attributes_for :tags, allow_destroy: true, reject_if: lambda {|attrs| attrs.all? {|key, value| value.blank?}}
end
followed by:
class User < ActiveRecord::Base
has_many :posts
attr_accessible :codename, :password, :password_confirmation
end
There is a third model ‘Tags’ which has a belongs_to post but that does not appear to be causing the problem. There is also a SessionsController with new,create, and destroy actions (code below).
The find_user method is run only on the new and create actions in the PostsController
before_filter :find_user
def find_user
@user = User.find(params[:user_id])
end
def new
@post = @user.posts.build(tags: Tag.new)
respond_to do |format|
format.html
end
end
def create
@post = @user.posts.build(params[:post])
@tags = @post.tags.build(params[:tags])
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
else
format.html { render action: :new }
end
end
end
and the User.authenticate method / SessionsController create action
def self.authenticate(codename, password)
user = User.find_by_codename(codename)
unless user && user.authenticate(password)
raise "You are not who you say you are."
end
user
end
def create
session[:user_id] = User.authenticate(params[:codename], params[:password]).id
redirect_to action: session[:intended_action], controller: session[:intended_controller], success: "You're In!"
end
The problem seems to be easy – you storing id of authenticated User in session object, but trying to fetch user using
params[:user_id]instead ofsession[:user_id]