Ruby On Rails使用Active Record关联对象

时间:2012-02-24 00:05:54

标签: ruby-on-rails activerecord devise

我已经阅读了一些关于使用Active Record的教程和书籍,但我无法将各个部分捆绑在一起。我用devise创建了一个名为User的模型:

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

我使用scaffold创建任务:

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

当我尝试保存任务然后通过视图时,它抱怨对象是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"]

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

关闭但不完全在那里!这可能更符合您的要求:

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

或者您可以简化控制器中的问题,并在那里一步完成:

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

  ...