为什么 Rails 5 没有保存嵌套属性,因为父模型没有先保存
Why Rails 5 is not saving nested attributes because parent model is not saving first
我正在使用 Rails 5 及其最新的 stable 版本。所以我得到以下信息:
You have your association set to required but it's missing.
Associations are set to required by default in rails 5 so if you want
to keep one empty you need to set optional:true on your association in
mode
这很好,我明白发生了什么,但是对于我的生活,我无法弄清楚如何让父模型先保存,所以 user_id 被翻译成嵌套模型记录。我在上面到处都看到相同的答案,但是除了将初始化程序中的默认值从 true 更改为 false 之外,没有人解释解决方法。这不能解决问题,因为记录确实保存了,但它不包括 user_id.
下面是我的代码库,我想问而不是用上面的引述来回应,有人可以启发我如何在保存时将 USER_ID 字段放入嵌套属性中。我拒绝禁用验证并手动处理插入,因为这不是 ruby 方式并且违反标准!
提前感谢任何能够直接回答这个问题并且没有偏离 ruby 事物方式的模糊解释的人!
###Models
#Users
class User < ApplicationRecord
has_one :profile, inverse_of: :user
accepts_nested_attributes_for :profile, allow_destroy: true
end
#Profiles
class Profile < ApplicationRecord
belongs_to :user, inverse_of: :profile
end
###Controller
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
# GET /users
# GET /users.json
def index
@users = User.all
end
# GET /users/1
# GET /users/1.json
def show
end
# GET /users/new
def new
@user = User.new
@user.build_profile
end
# GET /users/1/edit
def edit
@user.build_profile
end
# POST /users
# POST /users.json
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
respond_to do |format|
if @user.update(user_params)
format.html { redirect_to @user, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: @user }
else
format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
@user.destroy
respond_to do |format|
format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:username, :password, :user_type_id, profile_attributes: [:user_id, :first_name, :middle_name, :last_name, :phone_number, :cell_number, :email])
end
end
##View
<%= form_for(@user) do |f| %>
<% if user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(user.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% user.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
<!--<li><%= debug f %></li>-->
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :username %>
<%= f.text_field :username %>
</div>
<div class="field">
<%= f.label :password %>
<%= f.text_field :password %>
</div>
<div class="field">
<% if params[:trainer] == "true" %>
<%= f.label :user_type_id %>
<%= f.text_field :user_type_id, :readonly => true, :value => '2' %>
<% else %>
<%= f.label :user_type_id %>
<%= f.text_field :user_type_id, :readonly => true, :value => '1' %>
<% end %>
</div>
<h2>Account Profile</h2>
<%= f.fields_for :profile do |profile| %>
<%#= profile.inspect %>
<div>
<%= profile.label :first_name %>
<%= profile.text_field :first_name %>
</div>
<div>
<%= profile.label :middle_name %>
<%= profile.text_field :middle_name %>
</div>
<div>
<%= profile.label :last_name %>
<%= profile.text_field :last_name %>
</div>
<div>
<%= profile.label :email %>
<%= profile.text_field :email %>
</div>
<div>
<%= profile.label :phone_number %>
<%= profile.telephone_field :phone_number %>
</div>
<div>
<%= profile.label :cell_phone %>
<%= profile.telephone_field :cell_number %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<%= debug params %>
<%= debug user %>
<%= debug user.profile %>
<% end %>
更新
对于初学者,我发现您需要将 autosave: true 包含在关系中,例如
class User < ApplicationRecord
has_one :profile, inverse_of: :user, autosave: true
accepts_nested_attributes_for :profile, allow_destroy: true
end
然后父记录先于子记录保存。现在出现了另一个我不确定的问题,并且在提交表单时很奇怪,您会在我粘贴在下面的控制台输出中注意到 INSERT INTO profiles
语句包括user_id 列和 1 的值。它通过了验证,看起来它从输出中正常运行,但是 user_id 列中的 profiles table 是仍然为空。我将继续挖掘,希望我的一位 rubyiests 能看到这一点,并对如何解决这个问题有一些想法。到目前为止,我喜欢 Rails 5 项改进,但如果没有有趣的小陷阱,它就不会是 ROR!再次感谢!
Started POST "/users" for 192.168.0.31 at 2017-03-12 22:28:14 -0400
Cannot render console from 192.168.0.31! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by UsersController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"YA7kQnScvlIBy5OiT+BmOQ2bR7J00ANXId38FqNwX37Cejd+6faUyD3rMF4y0qJNKBUYGaxrRZqcLrXonL6ymA==", "user"=>{"username"=>"john", "password"=>"[FILTERED]", "user_type_id"=>"1", "profile_attributes"=>{"first_name"=>"john", "middle_name"=>"r", "last_name"=>"tung", "email"=>"thegugaru@gmail.com", "phone_number"=>"8033207677", "cell_number"=>"8033207677"}}, "commit"=>"Create User"}
(0.1ms) BEGIN
SQL (0.3ms) INSERT INTO `users` (`username`, `password`, `user_type_id`, `created_at`, `updated_at`) VALUES ('john', '0000', 1, '2017-03-13 02:28:14', '2017-03-13 02:28:14')
SQL (0.4ms) INSERT INTO `profiles` (`user_id`, `email`, `first_name`, `middle_name`, `last_name`, `phone_number`, `cell_number`, `created_at`, `updated_at`) VALUES (1, 'thegu@gmail.com', 'john', 'r', 'tung', '8033207677', '8033207677', '2017-03-13 02:28:14', '2017-03-13 02:28:14')
(10.8ms) COMMIT
Redirected to http://192.168.0.51:3000/users/1
Completed 302 Found in 24ms (ActiveRecord: 11.5ms)
好的,我正在回答我自己的问题,因为我知道很多人都在为这个问题苦苦挣扎,而我实际上已经有了答案,而不是对文档的模糊回应。
首先,我们在此示例中仅使用一对一关系。创建关系时,您需要确保 parent 模型具有以下
- inverse_of:
- 自动保存:真
- accepts_nested_attributes_for:模型,allow_destroy:true
这是Users模型然后我会解释,
class User < ApplicationRecord
has_one :profile, inverse_of: :user, autosave: true
accepts_nested_attributes_for :profile, allow_destroy: true
end
in Rails 5 你需要 inverse_of: 因为这告诉 Rails 通过外键存在关系并且需要在保存你的嵌套模型时设置它表格数据。
现在,如果您离开关系线 autosave: true,您将得到 user_id not保存到配置文件 table 和其他列,除非你关闭验证然后它不会出错它只会保存它而没有 user_id .
这里发生的事情是 autosave: true 确保首先保存用户记录,以便它具有 user_id 存储在 profile 模型的嵌套属性中。
简而言之,这就是为什么 user_id 没有遍历到 child 并且它正在回滚而不是提交。
还有最后一个陷阱是有一些 posts 告诉你在你的控制器中你应该添加 @user.build_profile 这样的编辑路径我的 post 里有。不要这样做,他们大错特错了,在评估控制台输出后,它会导致
Started GET "/users/1/edit" for 192.168.0.31 at 2017-03-12 22:38:17 -0400
Cannot render console from 192.168.0.31! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by UsersController#edit as HTML
Parameters: {"id"=>"1"}
User Load (0.4ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
Profile Load (0.5ms) SELECT `profiles`.* FROM `profiles` WHERE `profiles`.`user_id` = 1 LIMIT 1
(0.1ms) BEGIN
SQL (0.5ms) UPDATE `profiles` SET `user_id` = NULL, `updated_at` = '2017-03-13 02:38:17' WHERE `profiles`.`id` = 1
(59.5ms) COMMIT
Rendering users/edit.html.erb within layouts/application
Rendered users/_form.html.erb (44.8ms)
Rendered users/edit.html.erb within layouts/application (50.2ms)
Completed 200 OK in 174ms (Views: 98.6ms | ActiveRecord: 61.1ms)
如果您看到它正在从头开始重建配置文件,并将与您正在编辑的当前用户匹配的记录的 user_id 重置为 null。
所以要非常小心,因为我看到很多 post 提出这个建议,我花了几天时间研究才找到解决方案!
我正在使用 Rails 5 及其最新的 stable 版本。所以我得到以下信息:
You have your association set to required but it's missing. Associations are set to required by default in rails 5 so if you want to keep one empty you need to set optional:true on your association in mode
这很好,我明白发生了什么,但是对于我的生活,我无法弄清楚如何让父模型先保存,所以 user_id 被翻译成嵌套模型记录。我在上面到处都看到相同的答案,但是除了将初始化程序中的默认值从 true 更改为 false 之外,没有人解释解决方法。这不能解决问题,因为记录确实保存了,但它不包括 user_id.
下面是我的代码库,我想问而不是用上面的引述来回应,有人可以启发我如何在保存时将 USER_ID 字段放入嵌套属性中。我拒绝禁用验证并手动处理插入,因为这不是 ruby 方式并且违反标准! 提前感谢任何能够直接回答这个问题并且没有偏离 ruby 事物方式的模糊解释的人!
###Models
#Users
class User < ApplicationRecord
has_one :profile, inverse_of: :user
accepts_nested_attributes_for :profile, allow_destroy: true
end
#Profiles
class Profile < ApplicationRecord
belongs_to :user, inverse_of: :profile
end
###Controller
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
# GET /users
# GET /users.json
def index
@users = User.all
end
# GET /users/1
# GET /users/1.json
def show
end
# GET /users/new
def new
@user = User.new
@user.build_profile
end
# GET /users/1/edit
def edit
@user.build_profile
end
# POST /users
# POST /users.json
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
respond_to do |format|
if @user.update(user_params)
format.html { redirect_to @user, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: @user }
else
format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
@user.destroy
respond_to do |format|
format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:username, :password, :user_type_id, profile_attributes: [:user_id, :first_name, :middle_name, :last_name, :phone_number, :cell_number, :email])
end
end
##View
<%= form_for(@user) do |f| %>
<% if user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(user.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% user.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
<!--<li><%= debug f %></li>-->
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :username %>
<%= f.text_field :username %>
</div>
<div class="field">
<%= f.label :password %>
<%= f.text_field :password %>
</div>
<div class="field">
<% if params[:trainer] == "true" %>
<%= f.label :user_type_id %>
<%= f.text_field :user_type_id, :readonly => true, :value => '2' %>
<% else %>
<%= f.label :user_type_id %>
<%= f.text_field :user_type_id, :readonly => true, :value => '1' %>
<% end %>
</div>
<h2>Account Profile</h2>
<%= f.fields_for :profile do |profile| %>
<%#= profile.inspect %>
<div>
<%= profile.label :first_name %>
<%= profile.text_field :first_name %>
</div>
<div>
<%= profile.label :middle_name %>
<%= profile.text_field :middle_name %>
</div>
<div>
<%= profile.label :last_name %>
<%= profile.text_field :last_name %>
</div>
<div>
<%= profile.label :email %>
<%= profile.text_field :email %>
</div>
<div>
<%= profile.label :phone_number %>
<%= profile.telephone_field :phone_number %>
</div>
<div>
<%= profile.label :cell_phone %>
<%= profile.telephone_field :cell_number %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<%= debug params %>
<%= debug user %>
<%= debug user.profile %>
<% end %>
更新 对于初学者,我发现您需要将 autosave: true 包含在关系中,例如
class User < ApplicationRecord
has_one :profile, inverse_of: :user, autosave: true
accepts_nested_attributes_for :profile, allow_destroy: true
end
然后父记录先于子记录保存。现在出现了另一个我不确定的问题,并且在提交表单时很奇怪,您会在我粘贴在下面的控制台输出中注意到 INSERT INTO profiles
语句包括user_id 列和 1 的值。它通过了验证,看起来它从输出中正常运行,但是 user_id 列中的 profiles table 是仍然为空。我将继续挖掘,希望我的一位 rubyiests 能看到这一点,并对如何解决这个问题有一些想法。到目前为止,我喜欢 Rails 5 项改进,但如果没有有趣的小陷阱,它就不会是 ROR!再次感谢!
Started POST "/users" for 192.168.0.31 at 2017-03-12 22:28:14 -0400
Cannot render console from 192.168.0.31! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by UsersController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"YA7kQnScvlIBy5OiT+BmOQ2bR7J00ANXId38FqNwX37Cejd+6faUyD3rMF4y0qJNKBUYGaxrRZqcLrXonL6ymA==", "user"=>{"username"=>"john", "password"=>"[FILTERED]", "user_type_id"=>"1", "profile_attributes"=>{"first_name"=>"john", "middle_name"=>"r", "last_name"=>"tung", "email"=>"thegugaru@gmail.com", "phone_number"=>"8033207677", "cell_number"=>"8033207677"}}, "commit"=>"Create User"}
(0.1ms) BEGIN
SQL (0.3ms) INSERT INTO `users` (`username`, `password`, `user_type_id`, `created_at`, `updated_at`) VALUES ('john', '0000', 1, '2017-03-13 02:28:14', '2017-03-13 02:28:14')
SQL (0.4ms) INSERT INTO `profiles` (`user_id`, `email`, `first_name`, `middle_name`, `last_name`, `phone_number`, `cell_number`, `created_at`, `updated_at`) VALUES (1, 'thegu@gmail.com', 'john', 'r', 'tung', '8033207677', '8033207677', '2017-03-13 02:28:14', '2017-03-13 02:28:14')
(10.8ms) COMMIT
Redirected to http://192.168.0.51:3000/users/1
Completed 302 Found in 24ms (ActiveRecord: 11.5ms)
好的,我正在回答我自己的问题,因为我知道很多人都在为这个问题苦苦挣扎,而我实际上已经有了答案,而不是对文档的模糊回应。
首先,我们在此示例中仅使用一对一关系。创建关系时,您需要确保 parent 模型具有以下
- inverse_of:
- 自动保存:真
- accepts_nested_attributes_for:模型,allow_destroy:true
这是Users模型然后我会解释,
class User < ApplicationRecord
has_one :profile, inverse_of: :user, autosave: true
accepts_nested_attributes_for :profile, allow_destroy: true
end
in Rails 5 你需要 inverse_of: 因为这告诉 Rails 通过外键存在关系并且需要在保存你的嵌套模型时设置它表格数据。
现在,如果您离开关系线 autosave: true,您将得到 user_id not保存到配置文件 table 和其他列,除非你关闭验证然后它不会出错它只会保存它而没有 user_id .
这里发生的事情是 autosave: true 确保首先保存用户记录,以便它具有 user_id 存储在 profile 模型的嵌套属性中。
简而言之,这就是为什么 user_id 没有遍历到 child 并且它正在回滚而不是提交。
还有最后一个陷阱是有一些 posts 告诉你在你的控制器中你应该添加 @user.build_profile 这样的编辑路径我的 post 里有。不要这样做,他们大错特错了,在评估控制台输出后,它会导致
Started GET "/users/1/edit" for 192.168.0.31 at 2017-03-12 22:38:17 -0400
Cannot render console from 192.168.0.31! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by UsersController#edit as HTML
Parameters: {"id"=>"1"}
User Load (0.4ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
Profile Load (0.5ms) SELECT `profiles`.* FROM `profiles` WHERE `profiles`.`user_id` = 1 LIMIT 1
(0.1ms) BEGIN
SQL (0.5ms) UPDATE `profiles` SET `user_id` = NULL, `updated_at` = '2017-03-13 02:38:17' WHERE `profiles`.`id` = 1
(59.5ms) COMMIT
Rendering users/edit.html.erb within layouts/application
Rendered users/_form.html.erb (44.8ms)
Rendered users/edit.html.erb within layouts/application (50.2ms)
Completed 200 OK in 174ms (Views: 98.6ms | ActiveRecord: 61.1ms)
如果您看到它正在从头开始重建配置文件,并将与您正在编辑的当前用户匹配的记录的 user_id 重置为 null。
所以要非常小心,因为我看到很多 post 提出这个建议,我花了几天时间研究才找到解决方案!