【问题标题】:Updating model in Rails doesn't associate it with user在 Rails 中更新模型不会将其与用户关联
【发布时间】:2014-03-31 03:13:54
【问题描述】:

当用户注册我的网站时,他们会自动点击注册向导(使用 WickedWizard gem)。他们输入的信息创建了一个 Finances 模型,该模型属于 User 模型。 User 模型 has_one Finance。

目前,当用户提交第一个财务表单时,页面会刷新而没有任何更新。当我查看我的日志时,我看到了这个:

 User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 2 ORDER BY "users"."id" ASC LIMIT 1
  Finance Load (0.1ms)  SELECT "finances".* FROM "finances" WHERE "finances"."user_id" = ? ORDER BY "finances"."id" ASC LIMIT 1  [["user_id", 2]]
   (0.1ms)  begin transaction
   (0.1ms)  rollback transaction
   (0.0ms)  begin transaction
   (0.1ms)  rollback transaction

这是财务注册向导控制器:

  def show
    if @finance.nil?
      @finance = current_user.build_finance
    else
      @finance = Finance.find_by_user_id current_user[:id]
        end
    render_wizard
  end

  def update
    @finance = current_user.build_finance
    @finance.update_attributes(finance_params)
    render_wizard @finance
  end

我还想考虑用户应该能够再次通过向导并从与之关联的财务模型中查看其数据的用例 - 这就是我认为 if @finance 的原因。零?节目中需要检查。

编辑

当前正在创建财务模型,但未与用户关联。

【问题讨论】:

  • 尝试在更新操作中在render_wizard 之前添加raise @finance.errors.inspect 并粘贴结果。
  • 看起来它现在正在创建财务模型,但并未将其与用户关联。

标签: ruby-on-rails ruby ruby-on-rails-4 wicked-gem


【解决方案1】:

尝试将您的代码更改为:

def show
  @finance = current_user.finance || current_user.build_finance
  render_wizard
end

def update
  @finance = current_user.finance || current_user.build_finance
  @finance.assign_attributes(finance_params)
  render_wizard @finance
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-10
    • 2014-04-06
    • 1970-01-01
    相关资源
    最近更新 更多