Ruby on Rails interview questions
14 questions with answers. 98 open jobs in India ask for Ruby on Rails.
Difference between string and text in rails?
The difference relies in how the symbol is converted into its respective column type in query language.
with MySQL :string is mapped to VARCHAR(255)
:string | VARCHAR | :limit => 1 to 255 (default = 255) :text | TINYTEXT, TEXT, MEDIUMTEXT, or LONGTEXT2 | :limit => 1 to 4294967296 (default = 65536)Reference:
When should each be used?
As a general rule of thumb, use
:stringfor short text input (username, email, password, titles, etc.) and use:textfor longer expected input such as descriptions, comment content, etc.From Stack Overflow: asked by Mo., answered by TJ Koblentz (CC BY-SA 4.0)
What is the easiest way to duplicate an activerecord record?
To get a copy, use the dup (or clone for < rails 3.1+) method:
#rails >= 3.1 new_record = old_record.dup # rails < 3.1 new_record = old_record.cloneThen you can change whichever fields you want.
ActiveRecord overrides the built-in Object#clone to give you a new (not saved to the DB) record with an unassigned ID.
Note that it does not copy associations, so you'll have to do this manually if you need to.From Stack Overflow: asked by Brent , answered by Michael Sepcot (CC BY-SA 4.0)
In Ruby on Rails, what's the difference between DateTime, Timestamp, Time and Date?
The difference between different date/time formats in ActiveRecord has little to do with Rails and everything to do with whatever database you're using.
Using MySQL as an example (if for no other reason because it's most popular), you have
DATE,DATETIME,TIMEandTIMESTAMPcolumn data types; just as you haveCHAR,VARCHAR,FLOATandINTEGER.So, you ask, what's the difference? Well, some of them are self-explanatory.
DATEonly stores a date,TIMEonly stores a time of day, whileDATETIMEstores both.The difference between
DATETIMEandTIMESTAMPis a bit more subtle:DATETIMEis formatted asYYYY-MM-DD HH:MM:SS. Valid ranges go from the year 1000 to the year 9999 (and everything in between. WhileTIMESTAMPlooks similar when you fetch it from the database, it's really a just a front for a unix timestamp. Its valid range goes from 1970 to 2038. The difference here, aside from the various built-in functions within the database engine, is storage space. BecauseDATETIMEstores every digit in the year, month day, hour, minute and second, it uses up a total of 8 bytes. AsTIMESTAMPonly stores the number of seconds since 1970-01-01, it uses 4 bytes.You can read more about the differences between time formats in MySQL here.
In the end, it comes down to what you need your date/time column to do:
- Do you need to store dates and times before 1970 or after 2038? => Use
DATETIME. - Do you need to worry about database size and you're within that timerange? => Use
TIMESTAMP. - Do you only need to store a date? => Use
DATE. - Do you only need to store a time? => Use
TIME.
Having said all of this, Rails actually makes some of these decisions for you. Both
:timestampand:datetimewill default toDATETIME, while:dateand:timecorresponds toDATEandTIME, respectively.This means that within Rails, you only have to decide whether you need to store date, time or both.
From Stack Overflow: asked by may, answered by vonconrad (CC BY-SA 4.0)
- Do you need to store dates and times before 1970 or after 2038? => Use
What is the difference between <%, <%=, <%# and -%> in ERB in Rails?
<% %>Executes the ruby code within the brackets.
<%= %>Prints something into erb file.
<%== %>Equivalent to
<%= raw %>. Prints something verbatim (i.e. w/o escaping) into erb file. (Taken from Ruby on Rails Guides.)<% -%>Avoids line break after expression.
<%# %>Comments out code within brackets; not sent to client (as opposed to HTML comments).
Visit Ruby Doc for more infos about ERB.
From Stack Overflow: asked by simo, answered by auralbee (CC BY-SA 4.0)
Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?
In Rails 3 and higher:
Rails.application.routes.url_helperse.g.
Rails.application.routes.url_helpers.posts_path Rails.application.routes.url_helpers.posts_url(host: 'example.com')Related documentation: ActionDispatch::Routing::UrlFor
From Stack Overflow: asked by Aaron Longwell, answered by Paul Horsfall (CC BY-SA 4.0)
What does bundle exec rake mean?
bundle execis a Bundler command to execute a script in the context of the current bundle (the one from your directory's Gemfile).rake db:migrateis the script where db is the namespace and migrate is the task name defined.So
bundle exec rake db:migrateexecutes the rake script with the commanddb:migratein the context of the current bundle.As to the "why?" I'll quote from the bundler page:
In some cases, running executables without
bundle execmay work, if the executable happens to be installed in your system and does not pull in any gems that conflict with your bundle.However, this is unreliable and is the source of considerable pain. Even if it looks like it works, it may not work in the future or on another machine.
From Stack Overflow: asked by JnBrymn, answered by ghoppe (CC BY-SA 3.0)
Rails :include vs. :joins
It appears that the
:includefunctionality was changed with Rails 2.1. Rails used to do the join in all cases, but for performance reasons it was changed to use multiple queries in some circumstances. This blog post by Fabio Akita has some good information on the change (see the section entitled "Optimized Eager Loading").From Stack Overflow: asked by Rob Cameron, answered by Greg Campbell (CC BY-SA 3.0)
raw vs. html_safe vs. h to unescape html
Considering Rails 3:
html_safeactually "sets the string" as HTML Safe (it's a little more complicated than that, but it's basically it). This way, you can return HTML Safe strings from helpers or models at will.hcan only be used from within a controller or view, since it's from a helper. It will force the output to be escaped. It's not really deprecated, but you most likely won't use it anymore: the only usage is to "revert" anhtml_safedeclaration, pretty unusual.Prepending your expression with
rawis actually equivalent to callingto_schained withhtml_safeon it, but is declared on a helper, just likeh, so it can only be used on controllers and views."SafeBuffers and Rails 3.0" is a nice explanation on how the
SafeBuffers (the class that does thehtml_safemagic) work.From Stack Overflow: asked by grautur, answered by Fábio Batista (CC BY-SA 3.0)
Rails 4: before_filter vs. before_action
As we can see in
ActionController::Base,before_actionis just a new syntax forbefore_filter.However the
before_filtersyntax is deprecated in Rails 5.0 and will be removed in Rails 5.1From Stack Overflow: asked by freemanoid, answered by freemanoid (CC BY-SA 4.0)
What is the best method of handling currency/money?
You'll probably want to use a
DECIMALtype in your database. In your migration, do something like this:# precision is the total number of digits # scale is the number of digits to the right of the decimal point add_column :items, :price, :decimal, :precision => 8, :scale => 2In Rails, the
:decimaltype is returned asBigDecimal, which is great for price calculation.If you insist on using integers, you will have to manually convert to and from
BigDecimals everywhere, which will probably just become a pain.As pointed out by mcl, to print the price, use:
number_to_currency(price, :unit => "€") #=> €1,234.01From Stack Overflow: asked by Barry Gallagher, answered by molf (CC BY-SA 3.0)
How can I rename a database column in a Ruby on Rails migration?
rename_column :table, :old_column, :new_columnYou'll probably want to create a separate migration to do this. (Rename
FixColumnNameas you will.):bin/rails generate migration FixColumnName # creates db/migrate/xxxxxxxxxx_fix_column_name.rbThen edit the migration to do your will:
# db/migrate/xxxxxxxxxx_fix_column_name.rb class FixColumnName < ActiveRecord::Migration def self.up rename_column :table_name, :old_column, :new_column end def self.down # rename back if you need or do something else or do nothing end endFor Rails 3.1 use:
While, the
upanddownmethods still apply, Rails 3.1 receives achangemethod that "knows how to migrate your database and reverse it when the migration is rolled back without the need to write a separate down method".See "Active Record Migrations" for more information.
rails g migration FixColumnName class FixColumnName < ActiveRecord::Migration def change rename_column :table_name, :old_column, :new_column end endIf you happen to have a whole bunch of columns to rename, or something that would have required repeating the table name over and over again:
rename_column :table_name, :old_column1, :new_column1 rename_column :table_name, :old_column2, :new_column2 ...You could use
change_tableto keep things a little neater:class FixColumnNames < ActiveRecord::Migration def change change_table :table_name do |t| t.rename :old_column1, :new_column1 t.rename :old_column2, :new_column2 ... end end endThen just
db:migrateas usual or however you go about your business.For Rails 4:
While creating a
Migrationfor renaming a column, Rails 4 generates achangemethod instead ofupanddownas mentioned in the above section. The generatedchangemethod is:$ > rails g migration ChangeColumnNamewhich will create a migration file similar to:
class ChangeColumnName < ActiveRecord::Migration def change rename_column :table_name, :old_column, :new_column end endFrom Stack Overflow: asked by user1994764, answered by nowk (CC BY-SA 4.0)
How do I get the current absolute URL in Ruby on Rails?
For Rails 3.2 or Rails 4+
You should use
request.original_urlto get the current URL. Source code on current repo found here.This method is documented at original_url method, but if you're curious, the implementation is:
def original_url base_url + original_fullpath endFor Rails 3:
You can write
"#{request.protocol}#{request.host_with_port}#{request.fullpath}", sincerequest.urlis now deprecated.For Rails 2:
You can write
request.urlinstead ofrequest.request_uri. This combines the protocol (usually http://) with the host, and request_uri to give you the full address.From Stack Overflow: asked by Jakub Arnold, answered by Jaime Bellmyer (CC BY-SA 4.0)
How can I rollback a specific migration?
rake db:rollback STEP=1Is a way to do this, if the migration you want to rollback is the last one applied. You can substitute 1 for however many migrations you want to go back.
For example:
rake db:rollback STEP=5Will also rollback all the migration that happened later (4, 3, 2 and also 1).
To roll back all migrations back to (and including) a target migration, use: (This corrected command was added after all the comments pointing out the error in the original post)
rake db:migrate VERSION=20100905201547In order to rollback only one specific migration (out of order) use:
rake db:migrate:down VERSION=20100905201547or
rails db:migrate:down VERSION=20100905201547Note that this will NOT rollback any interceding migrations -- only the one listed. If that is not what you intended, you can safely run
rake db:migrateand it will re-run only that one, skipping any others that were not previously rolled back.And if you ever want to migrate a single migration out of order, there is also its inverse
db:migrate:up:rake db:migrate:up VERSION=20100905201547From Stack Overflow: asked by AnApprentice, answered by Zachary Wright (CC BY-SA 4.0)
How to get a random number in Ruby?
Use
rand(range)From Ruby Random Numbers:
If you needed a random integer to simulate a roll of a six-sided die, you'd use:
1 + rand(6). A roll in craps could be simulated with2 + rand(6) + rand(6).Finally, if you just need a random float, just call
randwith no arguments.As Marc-André Lafortune mentions in his answer below (go upvote it), Ruby 1.9.2 has its own
Randomclass (that Marc-André himself helped to debug, hence the 1.9.2 target for that feature).For instance, in this game where you need to guess 10 numbers, you can initialize them with:
10.times.map{ 20 + Random.rand(11) } #=> [26, 26, 22, 20, 30, 26, 23, 23, 25, 22]Note:
Using
Random.new.rand(20..30)(usingRandom.new) generally would not be a good idea, as explained in detail (again) by Marc-André Lafortune, in his answer (again).But if you don't use
Random.new, then the class methodrandonly takes amaxvalue, not aRange, as banister (energetically) points out in the comment (and as documented in the docs forRandom). Only the instance method can take aRange, as illustrated by generate a random number with 7 digits.
This is why the equivalent of
Random.new.rand(20..30)would be20 + Random.rand(11), sinceRandom.rand(int)returns “a random integer greater than or equal to zero and less than the argument.”20..30includes 30, I need to come up with a random number between 0 and 11, excluding 11.From Stack Overflow: asked by Mark A. Nicolosi, answered by VonC (CC BY-SA 3.0)
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Stack Overflowby its contributors, named on each answerCC BY-SA14 questions