class User < ApplicationRecord
has_one :address, foreign_key: :user_id
accepts_nested_attributes_for :address
end
型号地址
class Address < ApplicationRecord
belongs_to :user, optional: true
end
控制器用户,一切都发生在这里
class UsersController < ApplicationController
def home # method which I use to display form
@user = User.find_by :id => session[:id]
end
def update # method for updating data
@user = User.find(session[:id])
if @user.update(user_params)
flash[:notice] = "Update successfully"
redirect_to home_path
else
flash[:error] = "Can not update"
redirect_to home_path
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password, images_attributes: [:image_link, :image_description], address_attributes: [:city, :street, :home_number, :post_code, :country])
end
end
更新形式:
<%= form_for @user, :html => { :id => "update-form", :class => "update-form"} do |f| %>
<%= f.text_field :name %>
<%= f.text_field :email %>
<%= f.fields_for :address do |a| %>
<%= a.text_field :city %>
<%= a.text_field :street %>
<%= a.number_field :home_number %>
<%= a.text_field :post_code %>
<%= a.text_field :country %>
<% end %>
<%= f.submit %>
<% end %>
当我提交我的表单时,它显示我一切都很好,我的意思是“更新成功”,但在数据库中它看起来像新记录被添加到地址表中,但用户表已正确更新。有人可以给我解释为什么?我在谷歌寻找答案,但没有任何帮助我。