Jay
Jay

Reputation: 86

Saving Date and Time from Form

Rails novice here, please forgive me if I'm missing something obvious.

I have a model called Game which has a datetime column in its table called occurred_at. As you might guess, information is meant to store the date/time at which a game occurred. So far, in creating my game objects, I have used seeds.rb to populate the occurred_at attribute by calling, Time.parse(str). (e.g. Time.parse("1 February 2017 5:00 PM PST"))

Now I'm working on the _form for the games#new and games#edit pages. This is (very basically) what I'd like the _form to look like:

<%= form_for @game do |f| %>
  <%= f.date_field :date %>
  <%= f.time_field :time %>
  <%= f.text_field :home_team %>
  <%= f.text_field :away_team %>
<% end %>

Obviously, this won't work. @game doesn't have date and time methods. The date and time of @game are accessed via @game.occurred_at. The intuitive solution is to pass date and time in my params and then add logic in my GamesController to create/update @game.occurred_at accordingly.

So I have three inquiries:

  1. Do I have the right idea as to the underlying solution of passing date and time parameters and combining them in GamesController? If not, what is the best way to accomplish the objective of updated :occurred_at?
  2. If my idea as to the underlying solution is correct, how would I go about implementing that in my application?
  3. Usually when an object is created or updated, the params are passed in the controller directly to the method responsible for the creation or update of the object. Does this affect my problem.

Upvotes: 0

Views: 3480

Answers (1)

Jeremie
Jeremie

Reputation: 2421

You have multiple choice to do this.

1/ Your answer could work, but you need to declare :date and :time as attributes accessor for it to work and the add the logic in your controller to combine the passed arguments into :occured_at

2/ You can use rails datetime_select http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-datetime_select

3/ Bit more complicated is to create all form input of the datetime object, but I am not sure this is the best solution.

EDIT: For your answer to work, you need to edit your model like this

class Game < ActiveRecord::Base
  attr_accessor :date, :time

  ... rest of your code
end

Then in the method of your controller:

game = params[:game]
date = game[:date]
time = game[:time]
occured_at = Time.parse "#{date} #{time}"
@game = Game.new(game)
@game.occured_at = occured_at
@game.save!

There is faster way to code this, but I purposely put each line for you to understand what is going on.

Upvotes: 3

Related Questions