【问题标题】:AbstractController::DoubleRenderError - unsure how to resolve [duplicate]AbstractController::DoubleRenderError - 不确定如何解决[重复]
【发布时间】:2015-10-26 06:37:40
【问题描述】:

很抱歉,这很明显,但我是 Rails 初学者,很难找到这个问题的答案。

我在创建操作时收到 AbstractController::DoubleRenderError,它应该同时创建一个新用户(接收他们的电子邮件地址、密码和密码确认)并创建一个新配置文件(接收许多其他首选项我要求用户在创建帐户时选择)。如果它们都已成功创建,我基本上想取回用户和配置文件 json,如果没有,则接收错误。

我知道我得到的错误是由于我有双“render json”行(if 下一个块,else 下一个块),但似乎无法确定如何将这两行合二为一.

  def create
    @user = User.new(register_params)
    @profile = Profile.new(profile_params)
    if @user.save && @profile.save
      render json: @user, status: :created, location: @user
      render json: @profile, status: :created, location: @profile
    else
      render json: @user.errors, status: :unprocessable_entity
      render json: @profile.errors, status: :unprocessable_entity
    end
  end

提前谢谢你!

【问题讨论】:

  • 欢迎来到 StackOverflow!有时,您不必根据阻碍您进步的错误进行搜索,而是根据您实际尝试做的事情进行搜索。我已经链接了相关问题,我投票关闭你的问题,因为它是重复的。你可能会想删除你的问题——不要。它包含解决同一问题的另一种方法,该方法未在链接问题中给出。

标签: ruby-on-rails ruby json


【解决方案1】:

你不能每个控制器渲染两次,如果你需要返回两个模型的结果你可以写这样的东西

def create
  @user = User.new(register_params)
  @profile = Profile.new(profile_params)
  if @user.save && @profile.save
    render json: user: @user, profile: @profile, status: :created
  else
    render json: user: @user.errors, profile: @profile.errors, status: :unprocessable_entity
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-27
    • 2014-07-02
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多