Search code examples
ruby-on-railsruby-on-rails-3rails-activerecordmodel-associations

ActiveRecords Associations: undefined method for nil:NilClass


first of all this is my first Rails application, so please be indulgent... I read the Rails Guides for associations in http://guides.rubyonrails.org/association_basics.html and then started to code my own project. My problem is that I can't do stuff like @project.user.email because @project.user seems to be nil all the time. This happen for all objects. @user.role.name also throws "undefined method for nil:NilClass"; I'm sure I'm doing wrong someting with the models definitions but I don't understand what it is. I appreciate your help. Thanks.

   class Role < ActiveRecord::Base
      has_many :users
      attr_accessible :name
   end

   class User < ActiveRecord::Base
      belongs_to :role
      has_many :projects
      attr_accessible :email, :password, :password_confirmation, :role_id, :role  
   end

   class Project < ActiveRecord::Base
      belongs_to :user
      belongs_to :project_type
      attr_accessible :id, :project_type_id, :title, :description  
   end

   class Project_Type < ActiveRecord::Base
      has_many :projects
      attr_accessible :name
   end

An example would be for instance the index view for projects where I do (HAML):

   %td= proyecto.user.email

which wouldn't work. However,

   %td= proyecto.user_id

does work fine.


Solution

  • When you create a new Project, all of the associations will default to nil unless you have setup some type of default in your migrations. There are a few things you can do there.

    First, you can set the user manually:

    @user = User.find(5)
    @project = Project.new
    @project.user = @user
    

    Additionally, you can build new projects from the user. The build method is added automatically from the has_many association.

    @user = User.find(5)
    @project = @user.projects.build
    

    Now @project will contain a project associated with the user who has id 5. You also need to be sure that you tell Rails what the associations are, otherwise the associations won't work.