简体   繁体   English

ROR:从一种形式更新两个模型

[英]ROR: Updating two models from one form

I have two models profiles and users on my form. 我的表单上有两个模型配置文件和用户。 After a user is created he can then move to editing his profile. 创建用户后,他可以继续编辑其个人资料。 The views work well. 意见很好。 But when I click Save to update the editted profile. 但是,当我单击“保存”以更新编辑的配置文件时。 It doesn't update, but the flash notice displays that profile has been updated. 它没有更新,但是闪存通知显示该配置文件已更新。 What might be wrong? 可能是什么问题? I'm not sure what went wrong. 我不确定出了什么问题。 Below is the code. 下面是代码。

class ProfilesController < ApplicationController

  def new
    #@user.profile = Profile.new
    @user = User.find(current_user.id)
    @identity = @user.profile || @user.build_profile()
    @identity.save
  end

  def update
    @user = current_user
    @identity = @user.profile
    if @identity.update_attributes(params[:identity])
      flash[:notice] = 'Profile was successfully updated.'
      redirect_to(new_profile_path())
    else
      render :action => "new"
    end
  end
end


class UsersController < ApplicationController

  def show
    @user = current_user
    @user = User.find(params[:id])
    @identity = @user.profile || @user.build_profile()
    @identity.save
  end

......

end

Thanks for your assistance. 谢谢你的协助。

There are potentially a few things wrong here. 这里可能存在一些错误。 But the best solution to this problem would be to simplify and use the built in rails features for editing associations. 但是,解决此问题的最佳方法是简化并使用内置的rails功能来编辑关联。

What I suggest doing is using nested attributes, Ryan Daigle has a great article on them . 我建议做的是使用嵌套属性, Ryan Daigle上有一篇很棒的文章

I'm not sure why you're calling save in a new action and not in a create , that doesn't feel right. 我不确定为什么您会在一个new操作中而不是在create调用save ,这感觉不对。 Also check that the name of the model in the form you're submitting is identity and not user or profile . 还要检查您提交的表单中的模型名称是否是identity而不是userprofile

Can a user exist without a profile? 没有配置文件的用户可以存在吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM