Ruby on Rails is a server-side web application development tool. Currently, it is one of the most popular frameworks and easy to learn. Even if it is easy to learn, programmers still get confused or get stuck at some point. Many questions start to arise and they look for the answers. So, we have prepared a list of 12 most asked questions about Ruby on Rails along with answers.

Contents

12 Most Asked Questions About Ruby on Rails

1. How to rename a database column in a Ruby on Rails migration?

2. How to understand nil vs. empty vs. blank in Rails (and Ruby)?

3. Why do people use Heroku when AWS is present? What distinguishes Heroku from AWS?

4. How to get the current absolute URL in Ruby on Rails?

5. Understanding the Rails Authenticity Token

6. How to rollback a specific migration?

7. How to get a random number in Ruby?

8. How to use concerns in Rails 4?

9. How to check if a specific key is present in a hash or not?

10. How to “pretty” format JSON output in Ruby on Rails?

11. Installing PostgreSQL on Ubuntu for Ruby on Rails

12. Difference between collection route and member route in ruby on rails?


1. How to rename a database column in a Ruby on Rails migration?

Answer:

rename_column :table, :old_column, :new_column

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

script/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”.

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

Alternative Answer:

You can also use rake db:rollback, then edit your migration and again run rake db:migrate.

However, if you have data in the column you don’t want to lose, then use rename_column.

2. How to understand nil vs. empty vs. blank in Rails (and Ruby)?

Answer:

.nil? can be used on any object and is true if the object is nil.

.empty? can be used on strings, arrays, and hashes and returns true if:

  • String length == 0
  • Array length == 0
  • Hash length == 0

Running .empty? on something that is nil will throw a NoMethodError.

That is where .blank? comes in. It is implemented by Rails and will operate on any object as well as work like .empty? on strings, arrays, and hashes.

nil.blank? == true
false.blank? == true
[].blank? == true
{}.blank? == true
"".blank? == true
5.blank? == false
0.blank? == false

.blank? also evaluates true on strings which are non-empty but contain only whitespace:

"  ".blank? == true
"  ".empty? == false

Rails also provides .present?, which returns the negation of .blank?.

Array gotcha: blank? will return false even if all elements of an array are blank. To determine blankness in this case, use all? with blank?, for example:

[ nil, '' ].blank? == false

[ nil, '' ].all? &:blank? == true

Alternative Answer:

This table will help you understand better:

enter image description here

blank?, present? are provided by Rails.

3. Why do people use Heroku when AWS is present? What distinguishes Heroku from AWS?

Answer:

AWS / Heroku are both free for small hobby projects (to start with).

If you want to start an app right away, without much customization of the architecture, then choose Heroku.

If you want to focus on the architecture and to be able to use different web servers, then choose AWS. AWS is more time-consuming based on what service/product you choose but can be worth it. AWS also comes with many plugin services and products.

Heroku

  • Platform as a Service (PAAS)
  • Good documentation
  • Has built-in tools and architecture.
  • Limited control over architecture while designing the app.
  • Deployment is taken care of (automatic via GitHub or manual via git commands or CLI).
  • Not time-consuming.

AWS

  • Infrastructure as a Service (IAAS)
  • Versatile – has many products such as EC2, LAMBDA, EMR, etc.
  • Can use a Dedicated instance for more control over the architecture, such as choosing the OS, software version, etc. There is more than one backend layer.
  • Elastic Beanstalk is a feature similar to Heroku’s PAAS.
  • Can use the automated deployment, or roll your own.

4. How to get the current absolute URL in Ruby on Rails?

Answer:

For Rails 3.2 or Rails 4+

You should use request.original_url to get the current URL.

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.

Alternative Answer:

You could use url_for(only_path: false)

5. Understanding the Rails Authenticity Token

Answer:

What happens

When the user views a form to create, update, or destroy a resource, the Rails app creates a random authenticity_token, stores this token in the session, and places it in a hidden field in the form. When the user submits the form, Rails looks for the authenticity_token, compares it to the one stored in the session, and if they match the request is allowed to continue.

Why it happens

Since the authenticity token is stored in the session, the client cannot know its value. This prevents people from submitting forms to a Rails app without viewing the form within that app itself. Imagine that you are using service A, you logged into the service and everything is ok. Now imagine that you went to use service B, and you saw a picture you like and pressed on the picture to view a larger size of it. Now, if some evil code was there at service B, it might send a request to service A (which you are logged into), and ask to delete your account, by sending a request to http://serviceA.com/close_account. This is what is known as CSRF (Cross Site Request Forgery).

If service A is using authenticity tokens, this attack vector is no longer applicable, since the request from service B would not contain the correct authenticity token, and will not be allowed to continue.

API docs describes details about meta tag:

CSRF protection is turned on with the protect_from_forgery method, which checks the token and resets the session if it doesn’t match what was expected. A call to this method is generated for new Rails applications by default. The token parameter is named authenticity_token by default. The name and value of this token must be added to every layout that renders forms by including csrf_meta_tags in the HTML head.

Notes

Keep in mind, Rails only verifies not idempotent methods (POST, PUT/PATCH and DELETE). GET request are not checked for authenticity token. Why? because the HTTP specification states that GET requests is idempotent and should not create, alter, or destroy resources at the server, and the request should be idempotent (if you run the same command multiple times, you should get the same result every time).

Also, the real implementation is a bit more complicated as defined in the beginning, ensuring better security. Rails does not issue the same stored token with every form. Neither does it generate and store a different token every time. It generates and stores a cryptographic hash in a session and issues new cryptographic tokens, which can be matched against the stored one, every time a page is rendered. See request_forgery_protection.rb.

Lessons

Use authenticity_token to protect your not idempotent methods (POST, PUT/PATCH, and DELETE). Also, make sure not to allow any GET requests that could potentially modify resources on the server.

Alternative Answer:

The authenticity token is designed so that you know your form is being submitted from your website. It is generated from the machine on which it runs with a unique identifier that only your machine can know, thus helping prevent cross-site request forgery attacks.

If you are simply having difficulty with rails denying your AJAX script access, you can use

<%= form_authenticity_token %>

to generate the correct token when you are creating your form.

You can read more about it in the documentation.

#ruby #ruby-on-rails #programming #developer #interview-questions

12 Most Asked Questions About Ruby On Rails
3.00 GEEK