ruby-on-rails interview questions
Top ruby-on-rails frequently asked interview questions
I would like my JSON output in Ruby on Rails to be "pretty" or nicely formatted. Right now, I call the to_json
method and my JSON is all on one line. At times this can be difficult to see if there is a problem in the JSON output stream.
Is there way to configure or a method to make my JSON "pretty" or nicely formatted in RoR?
Source: (StackOverflow)
The difference between rake db:migrate
and rake db:reset
is pretty clear in my head. The thing which I don't understand is how rake db:schema:load
different from the former two.
Just to be sure that I am on the same page:
rake db:migrate
- Runs the migrations which haven't been run yet.
rake db:reset
- Clears the database (presumably does a rake db:drop
+ rake db:create
+ rake db:migrate
) and runs migration on a fresh database.
Please help to clarify, if my understanding has gone wrong.
Source: (StackOverflow)
I find myself repeatedly looking for a clear definition of the differences of nil?
, blank?
, and empty?
in Ruby on Rails. Here's the closest I've come:
blank?
objects are false, empty, or a whitespace string. For example, ""
, " "
, nil
, []
, and {}
are blank.
nil?
objects are instances of NilClass.
empty?
objects are class-specific, and the definition varies from class to class. A string is empty if it has no characters, and an array is empty if it contains no items.
Is there anything missing, or a tighter comparison that can be made?
Source: (StackOverflow)
In my experience, getting dates/times right when programming is always fraught with danger and difficulity.
Ruby and Rails have always eluded me on this one, if only due to the overwhelming number of options; I never have any idea which I should pick.
When I'm using Rails and looking at ActiveRecord datatypes I can find the following
:datetime, :timestamp, :time, and :date
and have no idea what the differences are or where the gotchas lurk.
What's the difference? What do you use them for?
(P.S. I'm using Rails3)
Source: (StackOverflow)
I wrongly named a column hased_password
instead of hashed_password
.
How can update database scheme with using migration to rename this column?
Source: (StackOverflow)
I am running into some issues regarding Authenticity Token in rails, as I did many times now.
But I really don't want to just solve this problem and go on, I would really like to understand Authenticity token.
Well, my question is, do you have some complete source of information on this subject or would spend your time to explain in details here?
Source: (StackOverflow)
The default Rails 4 project generator now creates the directory "concerns" under controllers and models. I have found some explanations about how to use routing concerns, but nothing about controllers or models.
I am pretty sure it has to do with the current "DCI trend" in the community and would like to give it a try.
The question is, how am I supposed to use this feature, is there a convention on how to define the naming / class hierarchy in order to make it work? How can I include a concern in a model or controller?
Source: (StackOverflow)
How can I set default value in ActiveRecord?
I see a post from Pratik that describes an ugly, complicated chunk of code: http://m.onkey.org/2007/7/24/how-to-set-default-values-in-your-model
class Item < ActiveRecord::Base
def initialize_with_defaults(attrs = nil, &block)
initialize_without_defaults(attrs) do
setter = lambda { |key, value| self.send("#{key.to_s}=", value) unless
!attrs.nil? && attrs.keys.map(&:to_s).include?(key.to_s) }
setter.call('scheduler_type', 'hotseat')
yield self if block_given?
end
end
alias_method_chain :initialize, :defaults
end
I have seen the following examples googling around:
def initialize
super
self.status = ACTIVE unless self.status
end
and
def after_initialize
return unless new_record?
self.status = ACTIVE
end
I've also seen people put it in their migration, but I'd rather see it defined in the model code.
Is there a canonical way to set default value for fields in ActiveRecord model?
Source: (StackOverflow)
I have the following Rails 3 migration file db\migrate\20100905201547_create_blocks.rb
How can I specifically roll back that migration file?
Source: (StackOverflow)
I just updated to rails 4.0.2 and I'm getting this warning:
[deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message.
Is there any security issue in setting it to false?
Source: (StackOverflow)
I added a table that I thought I was going to need, but now no longer plan on using it. How should I remove that table?
I've already ran migrations, so the table is in my database. I figure rails generate migration
should be able to handle this, but I haven't figured out how yet.
I've tried
rails generate migration drop_tablename
, but that just generated an empty migration.
What is the "official" way to drop a table in Rails?
Source: (StackOverflow)
I made a basic rails app with a simple pages controller with an index function and when I load the page I get:
ActionView::Template::Error (application.css isn't precompiled):
2: <html>
3: <head>
4: <title>Demo</title>
5: <%= stylesheet_link_tag "application" %>
6: <%= javascript_include_tag "application" %>
7: <%= csrf_meta_tags %>
8: </head>
app/views/layouts/application.html.erb:5:in `_app_views_layouts_application_html_erb__43625033_88530400'
Gemfile
source 'http://rubygems.org'
gem 'rails', '3.1.0'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'sqlite3'
gem 'execjs'
gem 'therubyracer'
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', " ~> 3.1.0"
gem 'coffee-rails', "~> 3.1.0"
gem 'uglifier'
end
gem 'jquery-rails'
# Use unicorn as the web server
# gem 'unicorn'
# Deploy with Capistrano
# gem 'capistrano'
# To use debugger
# gem 'ruby-debug19', :require => 'ruby-debug'
group :test do
# Pretty printed test output
gem 'turn', :require => false
end
Source: (StackOverflow)
I've recently started programming in Ruby, and I am looking at exception handling.
I was wondering if ensure
was the Ruby equivalent of finally
in C#? Should I have:
file = File.open("myFile.txt", "w")
begin
file << "#{content} \n"
rescue
#handle the error here
ensure
file.close unless file.nil?
end
or should I do this?
#store the file
file = File.open("myFile.txt", "w")
begin
file << "#{content} \n"
file.close
rescue
#handle the error here
ensure
file.close unless file.nil?
end
Does ensure
get called no matter what, even if an exception isn't raised?
Source: (StackOverflow)
To my understanding, all of your javascript gets merged into 1 file. Rails does this by default when it adds //= require_tree .
to the bottom of your application.js
manifest file.
This sounds like a real life-saver, but I am a little concerned about page-specific javascript code. Does this code get executed on every page? The last thing I want is for all of my objects to be instantiated for every page when they are only needed on 1 page.
Also, isn't there potential for code that clashes too?
Or do you put a small script
tag at the bottom of the page that just calls into a method that executes the javascript code for the page?
Do you no longer need require.js then?
Thanks
EDIT: I appreciate all the answers... and I don't think they are really getting at the problem. Some of them are about styling and don't seem to relate... and others just mention javascript_include_tag
... which I know exists (obviously...) but it would appear that the Rails 3.1 way going forward is to wrap up all of your Javascript into 1 file rather than loading individual Javascript at the bottom of each page.
The best solution I can come up with is to wrap certain features in div
tags with id
s or class
es. In the javascript code, you just check if the id
or class
is on the page, and if it is, you run the javascript code that is associated with it. This way if the dynamic element is not on the page, the javascript code doesn't run - even though it's been included in the massive application.js
file packaged by Sprockets.
My above solution has the benefit that if a search box is included on 8 of the 100 pages, it will run on only those 8 pages. You also won't have to include the same code on 8 of the pages on the site. In fact, you'll never have to include manual script tags on your site anywhere ever again.
I think this is the actual answer to my question.
Source: (StackOverflow)
I've installed devise on my app and applied the following in my application.html.erb
file:
<div id="user_nav">
<% if user_signed_in? %>
Signed in as <%= current_user.email %>. This cannot be cheese?
<%= link_to 'Sign out', destroy_user_session_path %>
<% else %>
<%= link_to 'Register', new_user_registration_path %> or <%= link_to 'Sign in', new_user_session_path %>
<% end %>
</div>
I ran rake routes
and confirmed that all the routes are valid.
Also, in my routes.rb
file I have devise_for :users
and root :to => "home#index"
.
I get the following routing error when clicking the "Sign out" link:
No route matches "/users/sign_out"
Any ideas what's causing the error?
Source: (StackOverflow)