【问题标题】:1 error prohibited this stage from being saved: Project must exist1 个错误禁止保存此阶段:项目必须存在
【发布时间】:2020-01-15 05:51:58
【问题描述】:

我有一个保存项目名称的项目脚手架,并且我已经创建了与舞台脚手架的一对多关联。但是在创建项目后,当我尝试创建阶段时出现此错误-“项目必须存在”

项目.rb

class Project < ApplicationRecord
  validates :project_name, presence: true
  has_many :stages
end

stage.rb

class Stage < ApplicationRecord
  belongs_to :project
  validates :stage, :planned_start_date, :planned_end_date, :responsibility, presence: true
  has_many :tasks
end

schema.rb

  create_table "projects", force: :cascade do |t|
    t.string "project_name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "user_id"
  end

  create_table "stages", force: :cascade do |t|
    t.string "stage"
    t.date "planned_start_date"
    t.date "planned_end_date"
    t.date "actual_start_date"
    t.date "actual_end_date"
    t.string "responsibility"
    t.boolean "status"
    t.float "finance"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "project_id"
    t.index ["project_id"], name: "index_stages_on_project_id"
  end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 ruby-on-rails-5


    【解决方案1】:

    创建一个新的Stage。您需要提供Project,因为您在ProjectStage 之间有关联belongs_to 和has_many。因此,根据架构,您需要在 Stage 中提供 project_id

    你可以像这样创建舞台。

    @project = Project.find(your_porject_id)
    @stage = project.stages.create(your_stage_params)
    

    @project = Project.find(your_porject_id)
    @stage = project.stages.new(your_stage_params)
    @stage.save
    

    希望这会对你有所帮助。

    【讨论】:

    • 如果项目是可选的,只需将“可选:true”添加到belongs_to
    猜你喜欢
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 2014-11-05
    相关资源
    最近更新 更多