我对我认为的教科书更新示例感到困难。搜索了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以包含新操作。为什么新操作会影响编辑/更新操作?
答案 0 :(得分:0)
之前我遇到过类似的问题。我们能否看到您new
行动的代码?你有@user.build_profile
(@user = User.new
下方)吗?或者new
行动是否正常?