AnthonyGalli.com AnthonyGalli.com - 7 months ago 16
Ruby Question

Invalid date with Date.parse

Before a user signs up I require him to create a challenge.

This is challenges_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


The parameters are passed through:

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


The
action
and
deadline
parameters are passed as you can see above. But once the new user is created the new challenge is not created:

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


This is 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


Now if I change
deadline: Date.parse(deadline)
to
deadline: deadline
then the
challenge
is created upon creating the new user, but the
deadline
isn't saved for some reason:

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

Answer

The Challenge object won't save with an invalid deadline value. To use a text_field for a date, use the value option.

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

There is also date_field which returns a text field of type Date. The default value is generated by trying to call strftime("%Y-%m-%d") on the objects value. You are able to override strftime("%Y-%m-%d") by explicitly passing the value option (like above).

Comments