好的伙计们,Rails 5 确实有其细微差别与 Rails 4 不同。我所要做的是,每次我单击表单上的提交按钮时,它都会重新加载错误Profile user must exist and Profile user can't be blank。该表单加载良好,包括嵌套模型表单,但无论出于何种原因,它都无法在尝试将具有以下输出的子模型保存到控制台之前保存父模型:
Puma starting in single mode...
* Version 3.7.0 (ruby 2.2.6-p396), codename: Snowy Sagebrush
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop
Started POST "/users" for 192.168.0.31 at 2017-03-09 18:51:04 -0500
Cannot render console from 192.168.0.31! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
ActiveRecord::SchemaMigration Load (0.2ms) SELECT `schema_migrations`.* FROM `schema_migrations`
Processing by UsersController#create as HTML
Parameters: …Run Code Online (Sandbox Code Playgroud) ruby nested-forms nested-attributes nested-form-for ruby-on-rails-5
我正在使用 Rails 5 及其最新稳定版本的所有内容。所以我得到以下信息:
\n\n\n\n\n您已将关联设置为必需,但它丢失了。\n 在 Rails 5 中,默认情况下将关联设置为必需,因此,如果您想要\n 将其保留为空,则需要在\n 模式下对关联设置可选项:true
\n
这太棒了,我明白发生了什么,但是在我的一生中,我无法弄清楚如何让父模型首先保存,因此 user_id 被转换为嵌套模型记录。我在上面到处都看到了相同的答案,但是除了将初始化程序中的默认值从 true 更改为 false 之外,没有人解释解决方法。这并不能解决问题,因为记录确实保存了,但不包含 user_id。
\n\n下面是我的代码库,我想问而不是用上面的引用来回应,有人可以启发我如何在保存时将 USER_ID 字段放入嵌套属性中。我拒绝禁用验证并手动处理插入,因为这不是 ruby 方式并且违反了标准!\n提前感谢任何可以直接回答这个问题并且没有偏离 ruby 方式的模糊解释的人!
\n\n###Models\n#Users\nclass User < ApplicationRecord\n has_one :profile, inverse_of: :user\n accepts_nested_attributes_for :profile, allow_destroy: true\nend\n\n#Profiles\nclass Profile < ApplicationRecord\n belongs_to :user, inverse_of: :profile\nend\n\n###Controller\nclass UsersController < ApplicationController\n before_action :set_user, only: [:show, :edit, :update, :destroy]\n\n # GET /users\n # GET /users.json\n def index\n @users = User.all\n end\n\n # GET /users/1\n # GET /users/1.json\n def …Run Code Online (Sandbox Code Playgroud) activerecord ruby-on-rails nested-forms nested-attributes ruby-on-rails-5