Lee
Lee

Reputation: 20934

Rails 3 Checking a relationship count

I have a User & Profile Models. A user has_one profile IE.

class User < ActiveRecord::Base
  has_secure_password

  # Relationships
  has_one :profile

class Profile < ActiveRecord::Base

  # Relationships
  belongs_to :user

I am then trying to test to see if the user has a profile. If not redirect them to the profile controller ie.

class User::BaseController < ApplicationController

  # Filters
  before_filter :check_for_profile

  # Layout
  layout "backend"

  # Helpers
  helper_method :current_user

  private

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  def check_for_profile
    if current_user.profile.empty?
      redirect_to new_user_profile_path, :notice => "Please create a profile first."
    end
  end

end

No matter what I try I'm getting the error.

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.empty?

I'm pretty sure my relationships are right. Can anyone shed some light on what I'm doing wrong ?

Thank you in advance.

Lee

Upvotes: 0

Views: 192

Answers (2)

dmonopoly
dmonopoly

Reputation: 3331

Check out the "blank?" method at the following link. The "present?" method should also be considered - they're basically the same.

http://api.rubyonrails.org/classes/Object.html#method-i-blank-3F

Upvotes: 1

numbers1311407
numbers1311407

Reputation: 34072

try profile.blank? instead. empty? is not defined for nil.

Upvotes: 1

Related Questions