Let me preface by saying i’m a total noob at ruby/rails.
For some reason, I am just not grasping the concept of has_one &
belongs_to…
I’m working on a project that includes user authentication, and 3
different types of user profiles.
User profiles are either “fan”, “band”, or “venue” objects, and user
logins are “user” objects.
Just working with the “fan” profiles now.
I have the following tables:
table fans:
id
name
url
…
(etc)
…
user_id (foreign key)
table users:
id
login
hashed_password
email
salt
created_at
In User model:
class User < ActiveRecord::Base
has_one :fan
In Fan model:
class Fan < ActiveRecord::Base
belongs_to :user
in user_controller.rb:
def signup
@user = User.new(@params[:user])
if request.post?
if @user.save
session[:user] = User.authenticate(@user.login,
@user.password)
flash[:message] = “Signup successful”
redirect_to :controller => ‘fan’, :action => “new”
else
flash[:warning] = “Signup unsuccessful”
end
end
end
In fan_controller.rb:
def new
@fan = Fan.new
end
def create
@fan = Fan.new(params[:id])
@user.fan << @fan
if @fan.save
flash[:notice] = ‘Your Fan Profile was successfully created.’
redirect_to :action => ‘list’
else
render :action => ‘new’
end
end
The goal is, when a new user signs up, after creating their login info,
they get to create their “fan” profile, and when it is saved, the
profile is saved in the fans table, with the appropriate user_id
assigned to it.
As I currently have it, the user signup works, then takes me to the new
profile form, but when I try to save, I get:
NoMethodError in FanController#create
You have a nil object when you didn’t expect it!
The error occured while evaluating nil.fan
RAILS_ROOT: script/…/config/…
Application Trace | Framework Trace | Full Trace
#{RAILS_ROOT}/app/controllers/fan_controller.rb:28:in `create’
line 28 is ‘@user.fan << @fan’
i’ve tried @user.fan = @fan, that doesn’t work…
I keep reading and reading about this, and I just can’t seem to get a
handle on it yet. I’m in dire need of help!
much obliged,
Chad