Simon The Cat
Simon The Cat

Reputation: 654

Ruby On Rails Using Active Record to associate objects

I have read a few tutorials and in a book about using Active Record, but I am having trouble tying the pieces together. I used devise to create a model called User:

class User < ActiveRecord::Base
  has_many :tasks
  ....
end

I used scaffold to create Task:

class Task < ActiveRecord::Base
  belongs_to :user#, :autosave => true

  validates_presence_of :description, :date
  validates_numericality_of :hours

  def add_user(creating_user)
    user << creating_user
  end
end

task_controller.rb

# POST /tasks
  # POST /tasks.json
  def create
    @task = Task.new(params[:task])

    # add in user to task
    @task.add_user current_user

    respond_to do |format|
      if @task.save
       .... #default code
      end
    end
  end

When I try to save a task then through the view it complains about the object being nil:

NoMethodError in TasksController#create

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.<<
Rails.root: /home/steven/csc309/project/Source/TPHNN

Application Trace | Framework Trace | Full Trace
app/models/task.rb:8:in `add_user'
app/controllers/tasks_controller.rb:48:in `create'
Request

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"zSslFLGZ+dbwr1+TBlUtq1F89chUtlBSV3qTHe6G0yY=",
 "task"=>{"id"=>"-4",
 "hours"=>"1",
 "miles"=>"2",
 "description"=>"dd",
 "date(1i)"=>"2012",
 "date(2i)"=>"2",
 "date(3i)"=>"23",
 "date(4i)"=>"23",
 "date(5i)"=>"34"},
 "commit"=>"Create Task"}
Show session dump

_csrf_token: "zSslFLGZ+dbwr1+TBlUtq1F89chUtlBSV3qTHe6G0yY="
session_id: "31e12032237fb42146b5291ab01cf71f"
warden.user.user.key: ["User", [1], "$2a$10$9P8RUZvg6r4LNSRy5FOdFu"]

Thanks for the help

Upvotes: 1

Views: 503

Answers (1)

Veraticus
Veraticus

Reputation: 16064

Close but not quite there! This is probably more what you want:

class Task < ActiveRecord::Base
  belongs_to :user#, :autosave => true

  validates_presence_of :description, :date
  validates_numericality_of :hours

  def add_user(creating_user)
    user = creating_user
  end
end

Or you could simplify matters in your controller and do it all in one step there:

def create
  @task = current_user.tasks.new(params[:task])

  ...

Upvotes: 2

Related Questions