Dave
Dave

Reputation: 556

Rails NoMethodError trying to create an associated model

I'm from a Java/PHP background and I'm trying to learn Rails, but I'm finding the 'convention' stuff really tricky (it's maybe not helping that I'm mostly doing it without net access while on the train). This one has me really stumped - I've read the Association Basics guide and some tutorials, but I still can't get this exception to go away.

Models:

class JobSeeker < ActiveRecord::Base
  attr_accessible :fullName, :dob, :roleTagline, :expTagline, :phoneNumber,
            :country, :email

  belongs_to :user
end


class User < ActiveRecord::Base
  attr_accessor :password
  attr_accessible :username, :email, :password, :password_confirmation

  # other unrelated stuff ...

  has_one :job_seeker, :dependent => :destroy
end

User Controller:

class UsersController < ApplicationController

def create
  @user = User.new(params[:user])

  @job_seeker = @user.job_seeker.create(params[:user])
  if @user.save
    sign_in @user
    flash[:success] = "Welcome to the Sample App!"
    redirect_to @user
  else
    @title = "Sign up"
    render 'home/index'
  end
end

Exception:

NoMethodError in UsersController#create

undefined method `create' for nil:NilClass

The problem is the nil:NilClass, I think. It's like Rails doesn't know :job_seeker is a JobSeeker or something. I've tried renaming it to everything under the sun (:job_seekers, :jobSeeker, etc.) but I'm a bit lost now.

The database table for JobSeeker has an integer column called user_id.

I'm using Rails 3.1 on Windows.

I'm sure it's something simple, but I'd really appreciate any help. Thanks a lot!

Upvotes: 0

Views: 233

Answers (1)

Harish Shetty
Harish Shetty

Reputation: 64363

The has_one association does not support create method. Use create_association methods, i.e.

@job_seeker = @user.create_job_seeker(params[:user])

PS: I would rewrite your code to use build instead of create to avoid orphan JobSeeker objects when User save fails.

def create
  @user = User.new(params[:user])
  @job_seeker = @user.build_job_seeker(params[:user])
  if @user.save

  else

  end
end

Upvotes: 1

Related Questions