I have a class Event where I need a method that compares the current date to the date the Event was created. Can you tell me how to access the created_at timestamp the scaffold created for the Event database table?
class Event < ActiveRecord::Base
attr_accessible :location, :name
def isInsertedLongAgo
# current date - insertion date >= 90 days
end
end
Same as any other attribute - just call it:
def isInsertedLongAgo
# current date - insertion date >= 90 days
Time.now - created_at >= 90.days
end
Hi you can acces created at using created_at field self.created_at,
At the time of scaffold time stamp is created which create created_at,updated_at
You can directly access those variables.
replace insertion date with created_at
Related
I have the following table:
event_id value created_at updated_at
1 15.2 2014/01/01 00:00 2014/01/01 00:00
2 15.5 2014/01/01 00:10 2014/01/01 00:10
3 15.9 2014/01/01 00:20 2014/01/01 00:20
However, if a new Event has same value as the previous (as in newest in time) Event, then the previous Event should have "updated_at" set to current time and no new Event should be created.
In the example above, if I do Event.new(:value => 15.9), then Event with id 3 should have its updated_at set to current time - and that should be the only change.
Any suggestions on how to accomplish this? I have tried fiddling with Active Record callbacks, but fail when aborting creation (using rollback). It is of course possible to solve using a special "constructor" method, but I'd like to avoid that.
Event.where(value: params[:value]).first_or_create.touch
or in event.rb
before_save :update_if_existing
private
def update_if_existing
if event = Event.find_by(value: value)
event.touch # updates the updated_at timestamp if the existing event
false # prevents the current event from being inserted into the db
end
end
Event.find_or_create_by_value(params[:value]).touch
This method will find event by value or create one if event with this value doesn't exist. Touch method will update updated_at timestamp for this record.
You can do this way, let's say #event is the object and before saving you want to check the value
unless #event.value == Event.last.value
#event.save
else
Event.last.update_attributes(:updated_at => DateTime.now)
end
or you can do this in a single line using ternary operator
(#event.value == Event.last.value) ? (Event.last.update_attributes(:updated_at => DateTime.now)) : (#event.save)
Since your definition of Event is that no two events should have the same value - you should add a unique index on that field, which will also make any such operations much quicker.
Actually, since your event is not defined by its id but by its value, consider changing its primary key to value:
create_table(:event, :primary_key => 'value') do |t|
t.column :userID, :decimal, :null => false
...
end
class Event
set_primary_key :value
...
end
Now you can simply do:
Event.find_or_create_by_value(params[:value]).touch
If I make a model and create a field like "name" along with a Timestamp, will it be equivalent to a timestamp created manually through a query like:
CREATE TABLE whatever (
name varchar(25)
created timestamp NULL DEFAULT CURRENT_TIMESTAMP
)
In other words, if I'm dealing with a database that has the timestamp pre-created by hand, how do I create a model to match pre-existing records?
I imagine it's important so that I'm able to ActiveRecord queries without anything breaking on me.
ActiveRecord will understand the timestamp part of the schema so you should get an ActiveSupport::TimeWithZone out of the database just like you'd get with any other timestamp column. However, AR won't understand default current_timestamp so it will set your created column to NULL (or nil in Ruby land) and the default current_timestamp will never be triggered; I usually get around that with an after_initialize hook:
after_initialize :set_defaults, :if => :new_record?
#...
def set_defaults
self.created = Time.now
end
I am trying to do a very simple update on a field that does not have any validation whatsoever. However, the update always fails. Here is what the code looks like:
# model
class Event < ActiveRecord::Base
attr_accessible :start_time
..
end
# migration
class CreateEvents < ActiveRecord::Migration
def change
t.datetime :start_time
end
end
# console
Event.first.update_attribute(:start_time, "02:00")
The query that was run in the Rails log does not even include the start_time attribute!
(0.2ms) BEGIN
(4.5ms) UPDATE events SET updated_at =
'2012-07-24 19:51:33', repeat_days = '--- \n- wed\n- sat\n- sun\n',
event_date_list = '--- []\n\n' WHERE events.id = 3763
(5.5ms) COMMIT
I cannot begin to make sense of this. Can anyone help me understand the root cause of this problem?
You are a passing it a string, not a Date, Time, or Datetime object.
It looks like you just want to store the time, not the date attached. But maybe you meant to attach a date as well. If you want to store the date as well, look up the Datetime class.
If you want to store just the time (hours, minutes, and seconds), then I would suggest you change your start_time field to be an integer, and store the seconds: 2.hours or 2.hours + 4.minutes + 6.seconds.
You can convert that easily in to time again.
I am trying to figure out the best way to display all records by date. I have a date_due column in my database that is a datetime field.
So my output would include every date for which there is an entry, like this:
April 1, 2011
- Buy tickets
- Pickup groceries
April 2, 2011
- Call client
I am trying to use the following method, which is not working: find_all_by_date_due
What's the easiest way to do this in Rails?
Railscasts has a nice cast on group_by :
http://railscasts.com/episodes/29-group-by-month
You could make the dates into an association and assign it an arbitrary ID through rails.
class Entry
belongs_to :date
end
class Date
has_many :entries
end
#entry.date.build(:date => 2011-02-01 20:23:22)
#entry.find_by_date(2)
Date.find(2).date
=> 2011-02-01 20:23:22
I may have over-complicated what I need to do but this is what I now have.
I have a jobs controller that has 2 fields
starts_at as DATETIME
end_time as DATETIME
I save the event_date in a form using a
calendar_date_select :starts_at ,:time => false
I save the date time as
time_select :starts_at, {:twelve_hour => true}
This saves the Event date i.e 12/26/2009 and the start time as 7:00 pm
I need to also save the event end_time without having to re-enter the date, just the time
time_select :end_time, {:twelve_hour => true}
If i just use the above, the time is correct but the date dafaults to 01/01/2000
How do I save the date with the same date from starts_at?
In your controller, if the :end_time is nil, set it to the :starts_at variable like so:
object.end_time = object.starts_at unless not object.end_time.nil?
You may be able to shorten the end to
object.end_time = object.starts_at unless object.end_time.present?
but I'm not sure which version of Rails you are using and what the default implementation of .present? does for dates.
You could do this in the model or controller, but isn't it possible that an event will start late at night and end on the following day? To allow for this possibility I'd recommend having two calendar_date_selects and auto-assigning the ending date when the starting date is chosen (so the second calendar_date_select will rarely be used).
If you really don't want two calendars, maybe use a hidden field for the ending date that follows the start date.
I wouldn't enforce this same-date rule below the interface level unless you're absolutely sure different start and end dates will never occur.