【发布时间】:2017-07-04 15:18:42
【问题描述】:
在这两天猛烈抨击之后,我完全被难住了。我似乎无法为包含此(如下所述)或我之后添加的任何模型的任何模型保存任何数据。
我有一个如下所示的迁移:
class CreateScenarios < ActiveRecord::Migration[5.1]
def change
create_table :scenarios do |t|
t.string :title
t.text :description
t.string :scenariotype
t.references :activity, foreign_key: true
t.timestamps
end
end
end
我的架构:
create_table "scenarios", force: :cascade do |t|
t.string "title"
t.text "description"
t.string "scenariotype"
t.bigint "activity_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["activity_id"], name: "index_scenarios_on_activity_id"
end
模型如下所示:
class Scenario < ApplicationRecord
has_many :pages
belongs_to :activities
end
在我的控制器中,我设置了以下参数:
def scenario_params
params.require(:scenario).permit(:title, :description, :scenariotype, :activity_id)
end
新方法如下所示:
def new
@scenario = Scenario.new
@activity = Activity.find(params[:activity])
end
create 方法如下所示:
def create
@scenario = Scenario.new(scenario_params)
@activity = Activity.find(@scenario.activity_id)
@scenario.save
redirect_to new_page_path(scenario: @scenario.id)
end
当我尝试保存记录时,即使在控制台中,从这次迁移或任何以后的迁移中,它都不会保存并回滚,因为它不是自动递增的。所以运行这样的东西:
scenario=Scenario.new(:activity_id =>1, :title =>"asfdasdf", :scenariotype=>"Teaching", :description=>"asdfadsf")
结果是这样的
<Scenario id: nil, title: "asfdasdf", description: "asdfadsf", scenariotype: "Teaching", activity_id: 1, created_at: nil, updated_at: nil>
然后它回滚,因为它缺少一个 id。
我已经删除并重新创建了数据库。我认为以前的迁移可能有问题,但它们都工作得很好。我希望我错过了一些非常简单和愚蠢的东西,但我只是没有看到它。数据库是 Postgres。
提前感谢任何人提供的任何帮助。
【问题讨论】:
-
你有某种形式的@scenario 吗?
-
在运行迁移以创建 Scenario 表之前,您是否有一个名为 Activity 表的现有 Postgresql 表?
-
改为
@scenario.save!,然后粘贴上面的错误/警告。 -
只是另一个随机猜测,很可能是无关的,但有时 Rails 无法猜测单词的正确复数形式,例如“爱”=>“爱”而不是“爱”。在这种情况下,我们需要告诉 Rails 正确的复数形式。
-
你能告诉我们导致回滚的验证错误吗?写
scenario=Scenario.new(:activity_id =>1, :title =>"asfdasdf", :scenariotype=>"Teaching", :description=>"asdfadsf")然后写scenario.errors.full_messages在这里给我们结果
标签: ruby-on-rails postgresql ruby-on-rails-5