Get the time/date a record was created - ruby-on-rails

In Rails, is there an automatically instantiated field that has this information, or would I have to create a separate column in the model to keep track of it?

If you have columns called created_at and updated_at, they will update automatically. You can abbreviate that in your migration with t.timestamps, which now shows up by default (or did last time I created a model). If you're talking about an object stored in the database, there's no information about it other than what's in the table.
On a side note, if you're talking about an instance of an ActiveRecord it's best to say "record" instead of "object." The latter refers to any object that you instantiate, be it a record that you retrieve or just a simple Foo.new.

Rails automatically stores when each record is created in created_at it also stores when the record was last updated in updated_at

Related

Can Rails' "Validates Uniqueness" override an existing record with new one?

I have three time slots per day, and a bunch of candidate posts for publication. I'm making a little tool that lets us arrange candidates into slots for the next few weeks to see what the schedule might look like. We often have to rearrange, dragging one candidate from its current time slot to another one.
I have a model called PublishTime that pairs a candidate_id and a datetime. I know that I can set up the model to validate the uniqueness of both candidate_id and datetime, which would preserve uniqueness by preventing the creation of a new record that has an existing candidate_id or an existing datetime.
What I'd like to do instead is to preserve the uniqueness by deleting any existing records that have the candidate_id or datetime of the new record I'm creating. I'd like the new record to override any existing records. Is there a built-in way to do this?
I believe you can use find_or_initialize_by which is an upsert operation. If the record is new you insert it. If one already exists based on your requirements, you update it.
For example:
scope = params.slice(:candidate_id, :datetime)
publish_time = PublishTime.find_or_initialize_by(scope) do |new_publish_time|
# optional block if you need to do something with a new model
# do something with `new_publish_time`
end
publish_time.assign_attributes(params)
publish_time.save!

When last a table column was modified

Is there a way to know when a user updates a table column? For example, at what time a user changes their last name?
Im not interested when last a table was updated; only the column. Is it possible using Rails 5 and PostgreSQL?
If you are including timestamps in your models (.created_at and .updated_at) then .updated_at will tell you the last time that the record (i.e. the database row) was updated.
But that will not tell you which attribute of the record was changed (i.e. which database column). Nor will it tell you which user changed it, or if it was changed automatically by something in your system, etc.
You would need the schema to do that. You can a new table called as user_logs and implement a trigger which stores old_record and new_record. This will help you to get the desired log for change.

Rails - Is .first guaranteed to be the first created, or just the first fetched?

Let's assume I have many User records - if I call User.first is that guaranteed to be the first user that existed in the database or should I sort by created_at to make sure that the ordering is by created_at? Please note that I am using mongoid and not ActiveRecord.
User.first returns the first user ordered by primary key (see section 1.1.3 of Active Record Query Guide).
Most of the time it will be first created item, but it's not guaranteed. Depends on how the DB has been populated. So you should use:
Client.order('created_at').first
First returns the first object in the query. In your example calling User.first returns the first record in the User.all set of data. While this would by default be the first record in order of primary key, if you have placed any order conditions on the query (including a default scope on the model) it will return the first object based on the order given.
For example User.all.order("last_name").first would return the record with the first alphabetically ordered last name. Or User.all.order("updated_at DESC").first would return the most recently updated user.
If you have not set any ordering scopes on your query, the ordering will default to the order in which the records were created at and no other ordering would be necessary. For more info on the way these function, check out this rails guides entry on Active Record Query Interface.

Three ways to use user_id in a rails database, which one is best?

I have a rails application linked to a database table, which contains e-mail addresses and passwords. I would like to create a unique number which will identify each of the users in the system. This number will be given to a user upon registration, and stored in the field user_id on the same table.
So, for example, john#foo.bar could get 0001 as an ID, martha#foo.bar could get 0002, and so on.
My question is: what is the best way to do this?
Should I seed the database (rake db:seed) with the first user_id (0001) and write a method in the controller to +1 the user_id every time? If that is the case, how can I access the last row in order to find out the last user_id?
An alternative way would be to find the largest user_id in the table and +1 it. For that I guess I need to use tablename.find_by_user_id or something similar (would tablename.find_by_user_id.max work?)
A third way would be to store the latest user_id somewhere, and have the application retrive it when needed. Where could this information be stored?
I'm very new to rails . Would appreciate your feedback about which is the best way to go.
Thanks,
TimmyOnRails
Lets assume your model has two attributes name and email. Now by default rails will generate three more columns for you
1 id - auto incremental
2 created_at and updated_at - timestamps
Rake db:seed is one of the good solution in case you want to prepopulate the database. All you need to worry about is name and email. Add proper validations for these attributes. Rest rails will handle ie id is maintained by rails itself. You don't need to worry about it. Created_at and updated_at columns are also maintained by rails.
If you new to rails then I will suggest you to check http://railsforzombies.com and that will you a good idea about active records
Railsguides and RailsCasts are also two other learning materials for rails.

Rails - How to store each update of an item

I'm not sure how to do this in rails (maybe its a common topic but I'm not even sure if the title is correct)
I have a product table with this fields
Name
Quantity
Price
Size
and the columns that rails provide (id, created_at, updated_at)
This table is going to be updated periodically (lets say each day or so) but I want to save the QUANTITY that is being ADDED, and the date/time of the actualization (UPDATE).
I'm not sure if it's a design problem or something else.
Is there a way rails can handle this?
Thanks in advance
Javier QQ.
Given what you've said in your comments, why don't you just make a new table, say a "Stock" table. Each stock has two fields (in addition to the default created_at and updated_at): quantity and item_id.
Whenever you want to update an item with a new quantity, in the update method (or stock method, whatever it is) you do:
Stock.create(:item_id => #item.id, :quantity => params[:quantity])
This also ensures that you know when stock was added, because Rails will automatically keep track of when this Stock was made.
I'm not sure if this is exactly what you're looking for... but you can try the papertrail Gem. It stores each update of your model and you can easily step backwards or forwards in time through them to inspect your model and what fields changed, so it sounds like it'd be pretty ideal for what you have in mind.

Resources