Rails - ActiveModel :: MissingAttributeError

时间:2015-12-15 03:34:28

标签: ruby-on-rails

我使用create方法在此代码上收到以下错误。如果构建方法创建新的Project实例,为什么project_id不存在?

>      Failure/Error: project.save
>      
>      ActiveModel::MissingAttributeError:
>        can't write unknown attribute `project_id`

在create action中的save方法上生成错误:

class CreatesProject 

  attr_accessor :name, :task_string, :project 

  def initialize(name: "", task_string: "") 
    @name = name
    @task_string = task_string 
  end 

  def build
    self.project = Project.new(name: name) 
    project.tasks = convert_string_to_tasks 
    project 
  end 

  def convert_string_to_tasks
    task_string.split("\n").map do |task_string|
      title, size = task_string.split(":") 
      size = 1 if (size.blank? || size.to_i.zero?) 
      Task.new(title: title, size: size.to_i) 
    end
  end 

  def create
    build
    project.save
  end 
end 

这是项目模型关联。

class Project < ActiveRecord::Base
  attr_accessor :name
  has_many :tasks

 ...methods omitted since it is too long

end

这是任务模型关联。

class Task < ActiveRecord::Base
  attr_accessor :title, :size
  belongs_to :project


....omitted

end

这就是数据库中的模式对于任务而言的样子。

  create_table "tasks", force: :cascade do |t|
    t.integer  "project_id"
    etc.... 

任何可能导致此问题的想法?

0 个答案:

没有答案