2012-06-29 43 views
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以包含新的動作。爲什麼新操作會影響編輯/更新操作?

+0

亞歷克斯...你讓我思考,我意識到新的/創建的行動也無法正常工作。我在這裏發佈了另一個問題,[鏈接](http://stackoverflow.com/questions/11266125/multi-model-nested-form-cant-add-users-to-current-account)。一旦我弄清楚了,我會回到這個問題上(希望能回答它)。 – hugo

回答

0

我以前也有過類似的問題。我們能否看到您的new行動的代碼?你在那裏有@user.build_profile(在@user = User.new之下)?或者是new行動正常工作?