我很难理解我认为是教科书更新示例的内容。搜索SO但找不到答案。简而言之,当我单击提交时,配置文件模型中的 user_id 会被清除,并且不会保存其他数据。我正在使用 Rails 3.2.2。
这是我所拥有的...
用户模型...
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation, :profile_attributes
has_one :profile
accepts_nested_attributes_for :profile
end
轮廓模型...
class Profile < ActiveRecord::Base
validates :first_name, :presence => true
validates :last_name, :presence => true
belongs_to :user
attr_accessible :first_name, :last_name
end
用户控制器...
class UsersController < ApplicationController
def new
@user = User.new
@user.accounts_users.build()
@user.build_profile()
respond_to do |format|
format.html # new.html.erb
format.json { render json: @user }
end
end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
respond_to do |format|
if @user.update_attributes(params[:user])
format.html { redirect_to @user, notice: 'Profile was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
end
嵌套形式...
<%= form_for @user, :validate => true do |f| %>
<%= f.fields_for :profile do |p| %>
<fieldset>
<div class="field">
<%= p.label :first_name %>
<%= p.text_field :first_name %>
</div>
<div class="field">
<%= p.label :last_name %>
<%= p.text_field :last_name %>
</div>
<% end %>
<div class="field">
<%= f.label :email %>
<%= f.text_field :email %>
</div>
<div class="actions">
<%= f.submit 'Edit Profile', :class => "btn btn-large btn-success" %>
<%= cancel %>
</div>
</fieldset>
<% end %>
编辑:我编辑了 UsersController 以包含新操作。为什么新操作会影响编辑/更新操作?