ppaul74
ppaul74

Reputation: 751

Accessing has_many model records

I have the following 2 tables defined in migrations

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :name
      t.string :phone
      t.string :email
      t.string :address
      t.string :resume

      t.timestamps
   end
 end
end

Class CreateResumeSections < ActiveRecordMigration
   def self.up
     create_table :resume_sections do |t|
        t.string :section_name
        t.string :html
        t.timestamps
     end
   end
 end

I have following 2 models

class User
   has_many :resume_sections, :dependent => :destroy
   attr_accessor :section_layout
   after_save :save_sections

   private
   def save_sections
     self.section_layout = ###Someother logic here that sets this variable
   end

end

class ResumeSection
   belongs_to :user
end

In my users_controller, I have the following code

class UserController < ApplicationController
   def create
      @user = User.new(params[:user])
      @user.save 
      @user.section_layout.each {|key,value|
         rs = ResumeSection.new(:section_name => key, :html => value, :user => @user)
         rs.save
       }
   end
end

In my view I have the following code

 <% @user.resume_sections.each do |section| %>
<%= section.section_name %>
<%= section.html %>
 <% end %>

I get Undefined method error for Nil:NilClass in the view. The expression @user.resume_sections is not returning to me the records that I just created and saved in the UsersController. Instead it returns nil to me. When I check the database the records are there.

Is the expression @user.resume_sections the correct expression to access these records?

Thanks Paul

Upvotes: 0

Views: 166

Answers (1)

Matthew
Matthew

Reputation: 13332

It seems to me that your you missed something in you migrations. ResumeSection needs to have and integer field called user_id. Just create a new migration that has something like this in it:

def change
    add_column :resume_section, :user_id, :integer
end

Upvotes: 3

Related Questions