TasksController#中的NoMethodError在从项目创建新任务时创建

时间:2016-04-15 02:48:07

标签: ruby-on-rails ruby-on-rails-4 has-many-through nomethoderror

我有一个项目模型和一个任务模型,但是一个任务可以有很多项目,反之亦然......所以我创建了两者之间的关系模型。现在,从项目配置文件中,我希望能够创建任务并自动创建任务新任务与其创建项目之间的关系。

然而,当我尝试完成此操作时,我收到以下错误:

NoMethodError in TasksController#create
undefined method `related?' for nil:NilClass

我的任务控制器

class TasksController < ApplicationController

  def new
    @task = Task.new
  end

  def create
    @task = current_user.own_tasks.build(task_params)
    if @task.save
      flash[:success] = "Your task has been created."
      redirect_to @task
      @project.relate!(@task) unless @project.related?(@task) # establishes task relationship w/ project only if relationship doesn't already exist
    else
      render 'task'
    end
  end

private

def task_params
  params.require(:task).permit(:title, :description, :user_id, taskrelationship_attributes: [:taskproject_id, :projecttask_id])
end

end

我的TaskRelationship模型:

class TaskRelationship < ActiveRecord::Base
  belongs_to :taskproject, class_name: "Project"
  belongs_to :projecttask, class_name: "Task"
  validates :taskproject_id, presence: true
  validates :projecttask_id, presence: true
end

我的任务模型:

class Task < ActiveRecord::Base
  belongs_to :owner, :foreign_key=>'user_id', :class_name=>'User'

  has_many :reverse_taskrelationships, foreign_key: "projecttask_id",
                                   class_name: "TaskRelationship",
                                   dependent: :destroy
  has_many :taskprojects, through: :reverse_taskrelationships, source: :taskproject

  validates :title, presence: true
  validates :description, presence: true, length: { maximum: 140 }
end

端 项目模型:

class Project < ActiveRecord::Base
  belongs_to :owner, :foreign_key=>'user_id', :class_name=>'User'

  has_many :tasks
  has_many :taskrelationships, foreign_key: "taskproject_id", dependent: :destroy
  has_many :projecttasks, through: :taskrelationships, source: :projecttask

  validates :title, presence: true
  validates :background, presence: true

  def related?(some_task)
   taskrelationships.find_by_projecttask_id(some_task.id)
  end

  def relate!(some_task)
   self.taskrelationships.create!(projecttask_id: some_task.id)
  end
end

我不确定我哪里出错... thx,

更新:

我在create方法的顶部添加了以下行,因为marsAtomic指出缺少...

@project = Project.find(params[:id]) 

1 个答案:

答案 0 :(得分:2)

仔细查看错误:

undefined method `related?' for nil:NilClass

您尝试在nil对象上调用related?方法,在您的情况下,Project。您的create方法未在任何地方定义@project

更新:

您添加的代码:

@project = Project.find(params[:id])

将找不到正确的项目,因为param :id引用任务的ID而不是其关联的项目。请记住,你在tasks_controller.rb

如果每个任务都通过projecttask_id字段引用项目,则需要以下内容:

@project = Project.find(params[:projecttask_id])

请记住,projecttask_id是一种命名外键的奇怪方式。将它命名为project_id会不那么令人困惑。