日期无法更新,但返回为更新(Rails ActivereCord)



我有一个名为用户的导轨模型,该模型的生日字段在Postgres中具有类型日期。

我的第一个问题是我不确定如何更新用户的价值。如果我通过" 10/10/1980"之类的字符串,则不会更新。

第二个问题是,即使没有更新生日,rails也会返回用户。update(user_params)操作

我的两个问题:

  1. 如何更新日期字段?
  2. 如果通过不正确的日期?

如何更新日期字段?

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

  # 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 log(请注意,我在更新语句之后添加了一个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在保存之前将日期字符串解析到日期对象中,但是看起来不像self.birthday甚至在模型中出现。

将此行放在您的 applicationController

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

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

skip_before_action :verify_authenticity_token

最新更新