0
我很难与我认为会是一个教科书更新的例子。搜索到但无法找到答案。简而言之,当我点击提交时,配置文件模型中的user_id被清除,没有其他数据被保存。我正在使用Rails 3.2.2。嵌套模型,update_attributes不工作
这是我有...
用户模型...
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以包含新的动作。为什么新操作会影响编辑/更新操作?
亚历克斯...你让我思考,我意识到新的/创建的行动也无法正常工作。我在这里发布了另一个问题,[链接](http://stackoverflow.com/questions/11266125/multi-model-nested-form-cant-add-users-to-current-account)。一旦我弄清楚了,我会回到这个问题上(希望能回答它)。 – hugo