在抨击了两天之后,我完全被难住了。我似乎无法为包含此内容(如下所述)的任何模型或我之后添加的任何内容保存任何数据。
我有一个看起来像这样的迁移:
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
在我的 Controller 中,我设置了这些参数:
def scenario_params
params.require(:scenario).permit(:title, :description, :scenariotype, :activity_id)
end
新方法如下所示:
def new
@scenario = Scenario.new
@activity = Activity.find(params[:activity])
end
创建方法如下所示:
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。
提前感谢任何人可以提供的帮助。
最佳答案
您的场景模型有误 - 在设置 belongs_to
关联时,应使用单数形式。因此,您的模型应该如下所示,而不是 belongs_to :activities
:
class Scenario < ApplicationRecord
has_many :pages
belongs_to :activity
end
关于ruby-on-rails - Rails 5 不保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44909533/