Date.parse的日期无效

时间:2016-02-28 19:46:48

标签: ruby-on-rails ruby date

在用户注册之前,我要求他创建挑战。

这是challenge_controller:

def create
  @challenge = Challenge.new(challenge_params)
  if current_user == nil
    session[:challenge_action] = challenge_params[:action]
    session[:challenge_deadline] = [params["challenge"]["deadline(3i)"], params["challenge"]["deadline(2i)"], params["challenge"]["deadline(1i)"]].join('/')
    redirect_to signup_path
  end
end

参数传递:

  Parameters: {"challenge"=>{"action"=>"Run", "deadline"=>"2016-02-29"}, "button"=>""}

如上所示,传递actiondeadline参数。但是一旦创建了新用户,就不会创建新的挑战:

ArgumentError (invalid date):
  app/controllers/users_controller.rb:33:in `parse'
  app/controllers/users_controller.rb:33:in `create'

这是users_controller:

  def create
    @user = User.new(user_params)
    if @user.save
      action = session.delete(:challenge_action)
      deadline = session.delete(:challenge_deadline)
      # Create
      if deadline.present?
        @user.challenges.create(
          action: action,  
          deadline: Date.parse(deadline), #Focus of Question
        )
      end
      log_in @user
      redirect_to root_url
  end

现在,如果我将deadline: Date.parse(deadline)更改为deadline: deadline,则会在创建新用户时创建challenge,但由于某种原因deadline未被保存:

pry(main)> Challenge.last
 id: 1,
 action: "Code",
 deadline: nil,>

1 个答案:

答案 0 :(得分:1)

Challenge对象无法使用无效的截止日期值进行保存。要使用text_field作为日期,请使用值选项。

<%= f.text_field :deadline, value: @challenge.deadline.strftime("%d-%m-%Y") %>

还有date_field返回Date类型的文本字段。通过尝试在对象值上调用strftime("%Y-%m-%d")来生成默认值。您可以通过显式传递值选项(如上所述)来覆盖strftime("%Y-%m-%d")