All topics

Ruby on Rails interview questions

14 questions with answers. 98 open jobs in India ask for Ruby on Rails.

  1. 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:

    https://hub.packtpub.com/working-rails-activerecord-migrations-models-scaffolding-and-database-completion/

    When should each be used?

    As a general rule of thumb, use :string for short text input (username, email, password, titles, etc.) and use :text for longer expected input such as descriptions, comment content, etc.

    From Stack Overflow: asked by Mo., answered by TJ Koblentz (CC BY-SA 4.0)

  2. 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.clone
    

    Then 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.

    Rails 3.1 clone is a shallow copy, use dup instead...

    From Stack Overflow: asked by Brent , answered by Michael Sepcot (CC BY-SA 4.0)

  3. 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, TIME and TIMESTAMP column data types; just as you have CHAR, VARCHAR, FLOAT and INTEGER.

    So, you ask, what's the difference? Well, some of them are self-explanatory. DATE only stores a date, TIME only stores a time of day, while DATETIME stores both.

    The difference between DATETIME and TIMESTAMP is a bit more subtle: DATETIME is formatted as YYYY-MM-DD HH:MM:SS. Valid ranges go from the year 1000 to the year 9999 (and everything in between. While TIMESTAMP looks 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. Because DATETIME stores every digit in the year, month day, hour, minute and second, it uses up a total of 8 bytes. As TIMESTAMP only 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 :timestamp and :datetime will default to DATETIME, while :date and :time corresponds to DATE and TIME, 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)

  4. 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)

  5. Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

    In Rails 3 and higher:

    Rails.application.routes.url_helpers
    

    e.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)

  6. What does bundle exec rake mean?

    bundle exec is a Bundler command to execute a script in the context of the current bundle (the one from your directory's Gemfile). rake db:migrate is the script where db is the namespace and migrate is the task name defined.

    So bundle exec rake db:migrate executes the rake script with the command db:migrate in the context of the current bundle.

    As to the "why?" I'll quote from the bundler page:

    In some cases, running executables without bundle exec may 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)

  7. Rails :include vs. :joins

    It appears that the :include functionality 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)

  8. raw vs. html_safe vs. h to unescape html

    Considering Rails 3:

    html_safe actually "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.

    h can 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" an html_safe declaration, pretty unusual.

    Prepending your expression with raw is actually equivalent to calling to_s chained with html_safe on it, but is declared on a helper, just like h, 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 the html_safe magic) work.

    From Stack Overflow: asked by grautur, answered by Fábio Batista (CC BY-SA 3.0)

  9. Rails 4: before_filter vs. before_action

    As we can see in ActionController::Base, before_action is just a new syntax for before_filter.

    However the before_filter syntax is deprecated in Rails 5.0 and will be removed in Rails 5.1

    From Stack Overflow: asked by freemanoid, answered by freemanoid (CC BY-SA 4.0)

  10. What is the best method of handling currency/money?

    You'll probably want to use a DECIMAL type 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 => 2
    

    In Rails, the :decimal type is returned as BigDecimal, 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.01
    

    From Stack Overflow: asked by Barry Gallagher, answered by molf (CC BY-SA 3.0)

  11. How can I rename a database column in a Ruby on Rails migration?
    rename_column :table, :old_column, :new_column
    

    You'll probably want to create a separate migration to do this. (Rename FixColumnName as you will.):

    bin/rails generate migration FixColumnName
    # creates  db/migrate/xxxxxxxxxx_fix_column_name.rb
    

    Then 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
    end
    

    For Rails 3.1 use:

    While, the up and down methods still apply, Rails 3.1 receives a change method 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
    end
    

    If 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_table to 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
    end
    

    Then just db:migrate as usual or however you go about your business.

    For Rails 4:

    While creating a Migration for renaming a column, Rails 4 generates a change method instead of up and down as mentioned in the above section. The generated change method is:

    $ > rails g migration ChangeColumnName
    

    which will create a migration file similar to:

    class ChangeColumnName < ActiveRecord::Migration
      def change
        rename_column :table_name, :old_column, :new_column
      end
    end
    

    From Stack Overflow: asked by user1994764, answered by nowk (CC BY-SA 4.0)

  12. How do I get the current absolute URL in Ruby on Rails?

    For Rails 3.2 or Rails 4+

    You should use request.original_url to 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
    end
    

    For Rails 3:

    You can write "#{request.protocol}#{request.host_with_port}#{request.fullpath}", since request.url is now deprecated.

    For Rails 2:

    You can write request.url instead of request.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)

  13. How can I rollback a specific migration?
    rake db:rollback STEP=1
    

    Is 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=5
    

    Will 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=20100905201547
    

    In order to rollback only one specific migration (out of order) use:

    rake db:migrate:down VERSION=20100905201547
    

    or

    rails db:migrate:down VERSION=20100905201547
    

    Note 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:migrate and 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=20100905201547
    

    From Stack Overflow: asked by AnApprentice, answered by Zachary Wright (CC BY-SA 4.0)

  14. 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 with 2 + rand(6) + rand(6).

    Finally, if you just need a random float, just call rand with no arguments.

    As Marc-André Lafortune mentions in his answer below (go upvote it), Ruby 1.9.2 has its own Random class (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:

    This is why the equivalent of Random.new.rand(20..30) would be 20 + Random.rand(11), since Random.rand(int) returns “a random integer greater than or equal to zero and less than the argument.” 20..30 includes 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.