【问题标题】:Nested model, update_attributes not working嵌套模型,update_attributes 不起作用
【发布时间】:2012-06-29 10:25:54
【问题描述】:

我很难理解我认为是教科书更新示例的内容。搜索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 以包含新操作。为什么新操作会影响编辑/更新操作?

【问题讨论】:

  • Alex...你让我思考,我意识到新/创建操作也不起作用。我在这里发布了另一个问题,link。一旦我弄清楚了,我会回到这个问题(并希望能回答它)。

标签: ruby-on-rails nested-forms update-attributes


【解决方案1】:

我之前也遇到过类似的问题。我们可以查看您的new 操作的代码吗?你有@user.build_profile 吗(在@user = User.new 的正下方)?或者new 操作是否正常?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多