【问题标题】:Date failing to update, but returning true for Update (Rails ActiveRecord)日期未能更新,但更新返回 true (Rails ActiveRecord)
【发布时间】:2018-05-21 10:58:04
【问题描述】:

我有一个名为 user 的 Rails 模型,它在 Postgres 中有一个 date 类型的生日字段。

我的第一个问题是我不确定如何更新用户的价值。如果我传入像“10/10/1980”这样的字符串,它不会更新。

第二个问题是,即使生日没有更新,Rails 也会为 User.update(user_params) 操作返回 true

我的两个问题:

  1. 如何更新日期字段?
  2. 如果传入的日期不正确,如何确保 rails 抛出错误?

如何更新日期字段?

从下面的控制器更新方法。脚手架相当标准。

  # PATCH/PUT /users/1
  # PATCH/PUT /users/1.json
  def update
    respond_to do |format|
      puts(user_params)
      if @user.update(user_params)
        format.html { redirect_to @user, notice: 'User was successfully updated.' }
        format.json { render :show, status: :ok, location: @user }
      else
        format.html { render :edit }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

编辑:参数:

  def user_params
    params.require(:user)
          .permit(:points, :payment_option, :first_name, :last_name,
                  :payment_email, :phone_number, :facebook_id, :profile_pic_url,
                  :locale, :timezone, :gender, :email, :country, :city,
                  :age_group, :birthday, :employment_status, :occupation,
                  :education_level, :income_bracket)
  end

Rails 日志(请注意,我在更新语句后添加了 puts(user_params)。

Started PATCH "/api/v1/users/1" for 127.0.0.1 at 2017-12-07 19:16:37 +0800
Processing by UsersController#update as JSON
  Parameters: {"user"=>{"birthday"=>"12dsafkljfsldk"}, "id"=>"1"}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
Can't verify CSRF token authenticity.
{"birthday"=>"10/10/1900"}
   (0.2ms)  BEGIN
   (0.1ms)  COMMIT
  Rendering users/show.json.jbuilder
  Rendered users/_user.json.jbuilder (0.6ms)
  Rendered users/show.json.jbuilder (1.6ms)
Completed 200 OK in 31ms (Views: 5.9ms | ActiveRecord: 3.1ms)

我希望在保存之前可以使用 before_update 将日期字符串解析为 Date 对象,但它看起来不像 self.birthday 甚至出现在模型中。

【问题讨论】:

  • 尽量不要写“字符串类型”的代码。如果您有约会,请使用 Date 类。不是字符串。无论如何,话虽如此 - 为什么它不保存?轨道日志说什么? @user.errors 是什么?你到底看到了什么行为——你说“它不保存”“它没有抛出错误”???!!根据您的代码,如果记录未保存,将呈现错误
  • 参数在来自另一台服务器的 HTTP 调用中作为 JSON 正文传入。
  • 至于我所看到的。我看到 @user.update(user_params) 正在返回 true,所以它是“保存”但 @user.birthday 仍然是空白的。 user_params 以 {"birthday"=>"10-10-1900"} 的形式参加通话
  • 你允许user_params中的日期吗?
  • @JCDJulian rails 日志中有什么? 始终在调试时查看日志。我的猜测 - 这只是一个猜测,因为您上面的代码示例不完整(user_params 是什么?)是该参数不是允许

标签: ruby-on-rails ruby postgresql activerecord ruby-on-rails-5


【解决方案1】:

将此行放入您的 ApplicationController

 protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }

如果它不起作用,那么。尝试跳过动作

skip_before_action :verify_authenticity_token

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多