3

I have an ajax post to create a new Meeting. I want to convert the string meeting_time into a datetime format in the controller before save.

I have tried this, but it is still saving meeting_time as a string:

def create

requestor = current_user
@meeting_with_params = meeting_params
@meeting_time = @meeting_with_params[:meeting_time]
@meeting_time = @meeting_time.to_datetime
@meeting_with_params[:meeting_time] = @meeting_time
#@meeting_with_params
@meeting = Meeting.new(@meeting_with_params)

respond_to do |format|
  if @meeting.save
    format.html { redirect_to home_url, notice: 'Your lex was successfully requested! Click Plan Meeting ' }
    format.json { render :show, status: :created, location: @meeting }
  else
    format.html { render :new }
    format.json { render json: @meeting.errors, status: :unprocessable_entity }
  end
end
end

The params being passed look like this:

Started POST "/meetings" for 127.0.0.1 at 2016-10-31 11:45:44 -0400
Processing by MeetingsController#create as */*
  Parameters: {"meeting"=>{"requestor_id"=>"1", "requestee_id"=>"2", "meeting_time"=>"2016-10-18 22:10:00", "accepted"=>"false", "status"=>"Active", "location"=>"Black Forest Restaurant", "location_address"=>"733 Fulton St, Brooklyn, NY 11217"}}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
   (0.1ms)  begin transaction
  SQL (1.1ms)  INSERT INTO "meetings" ("requestor_id", "requestee_id", "meeting_time", "accepted", "location", "status", "location_address", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)  [["requestor_id", 1], ["requestee_id", 2], ["meeting_time", "2016-10-18 22:10:00.000000"], ["accepted", "f"], ["location", "Black Forest Restaurant"], ["status", "Active"], ["location_address", "733 Fulton St, Brooklyn, NY 11217"], ["created_at", "2016-10-31 15:45:44.557266"], ["updated_at", "2016-10-31 15:45:44.557266"]]

And the ajax call in in .js file:

$.ajax({
                url: '/meetings',
                type: 'POST',
                data: {
                    meeting: {
                        requestor_id: currentUserId,
                        requestee_id: requesteeId,
                        meeting_time: rubyDateTime,
                        accepted: false,
                        status: "Active",
                        location: meetingLocation,
                        location_address: meetingAddress
                    }
                },
                success: function(result)   {
                    createNotification(currentUserId, "Your meeting was successfully requested.");
                    location.reload();
                },
                error: function(err)    {
                    console.log(err);
                }
            })

How can I pull out meeting_time in the create controller, and change it to datetime before saving?

Thanks!!

****UPDATE I know it is not saving correctly because I also have a method that compares today's date with the meeting_time, and if it has passed, to do something. When saving directly to the database, it recognizes the times that have passed. When saving through the POST, with the exact same string, it does not since it is comparing 2 different types. The comparision controller:

def requestor_review_meeting
        @past_meetings = Meeting.where('meeting_time <= ? AND requestor_id= ? AND status = ? AND requestor_score < ?', DateTime.current, current_user, "Active", 1).order('meeting_time asc');
        render json: @past_meetings

end

And in console:

 > meeting_time
 => Tue, 18 Oct 2016 22:10:00 UTC +00:00 
2.1.2 :012 > meeting_time.class
 => ActiveSupport::TimeWithZone 
2.1.2 :013 > meeting_time.is_a?(DateTime)
 => false 
2.1.2 :015 > meeting_time.is_a?(Time)
=> true 
gwalshington
  • 1,418
  • 2
  • 30
  • 60
  • what is `meeting_time` db column type? – Aleksey Oct 31 '16 at 15:53
  • @Aleksey in the database, it is datetime. But since I can only pass a string through the ajax call, it is currently receiving a string. I need to convert to datetime before save. – gwalshington Oct 31 '16 at 15:54
  • What is the problem in your current code? How did you make sure it is still saving as string in DB? – Jayaprakash Oct 31 '16 at 15:58
  • I think it is just representation issue. Try to find the post and run call `meeting_time` method on it. What would be the output? – Aleksey Oct 31 '16 at 15:58
  • @Aleksey I updated my answer with more information that will hopefully help. Thanks! – gwalshington Oct 31 '16 at 16:24
  • if your database is not the same format as your application (like if it doesn't have timezone and you have to manually update it), you may have to do some work in the controller beyond ActiveRecord's getter/setter in the model. For cases like that, doing something like `before_action :sanitize_input, only: [:save,:create]` may be your friend. Then you can set something like `@meeting_time = Time.parse(params[:meeting_time]).now if params[:meeting_time]` – vol7ron Feb 26 '18 at 17:51

3 Answers3

2

ActiveRecord automatically type casts all inputs so they match the database schema. So even though the allow you to save meeting_time as a string, it will convert it to a datetime on load. If you're interested you can read more here

SomeSchmo
  • 665
  • 3
  • 18
  • - I updated my question with some more information on how I know the date isn't saving as the correct type. Hopefully this helps :/ – gwalshington Oct 31 '16 at 16:21
2

There is no need to convert the datetime string into datetime before save, because it will be saved as datetime automatically.

Ex)

User.create('Test user', '1990-10-31 11:45:44 0000')

Consider first field is user name and second one is DOB. The second one will be automatically parsed as datetime.

first string from above '1990-10-31' treated as date second string '11:45:44' treated as time and third string '0000' denotes timezone

1

It seems, your code looks fine. If you try to print meeting_time by querying the post, it should be datetime object.

Update

As said by @Rocco, the following is enough to save the data as Rails will convert the date string to date automatically from params.

def create

requestor = current_user
@meeting_with_params = meeting_params
@meeting = Meeting.new(@meeting_with_params)

respond_to do |format|
  if @meeting.save
    format.html { redirect_to home_url, notice: 'Your lex was successfully requested! Click Plan Meeting ' }
    format.json { render :show, status: :created, location: @meeting }
  else
    format.html { render :new }
    format.json { render json: @meeting.errors, status: :unprocessable_entity }
  end
end
end
Community
  • 1
  • 1
Jayaprakash
  • 1,407
  • 1
  • 9
  • 19
  • I updated my question with more information on why I can see it isn't saving in the right format. Thanks!! – gwalshington Oct 31 '16 at 16:23
  • Through your post, I figured out it's saving as Time, not DateTime. Can you suggest a way to correctly save as DateTime and not time? Merci – gwalshington Oct 31 '16 at 16:31
  • Both Time and Datetime type are similar. Check this http://stackoverflow.com/questions/1261329/whats-the-difference-between-datetime-and-time-in-ruby – Jayaprakash Oct 31 '16 at 16:32
  • If they are the same, then why does the query only work when it is saved as a datetime type, and not a time type? Is there a way to specify the type has to be datetime, since that is what it is categorized as in the schema? – gwalshington Oct 31 '16 at 16:37
  • The might be a timezone issue. Try to send the date as UTC always from AJAX calls, so that your comparison query will return the matching records always. – Jayaprakash Oct 31 '16 at 16:38