Ruby on Rails Q&A
1. Question: Explain the difference between a symbol and a string in Ruby.
Answer: A string is mutable and can be changed, while a symbol is immutable and cannot be changed. Symbols are often used as keys in hashes because they’re more memory efficient than strings.
2. Question: What is the difference between `render` and `redirect_to` in Rails?
Answer: render is used to create an HTTP response by combining the action’s template with the current state of the instance variables. redirect_to sends an HTTP redirect status code to the client and forces the client to issue a new request.
3. Question: How can you implement caching in Rails?
Answer: Rails provides several caching techniques: page, action, and fragment caching. For example, to cache a fragment of a view, you can use the cache helper:
#ruby
<% cache do %>
All the expensive computations
<% end %>
4. Question: What is CSRF and how does Rails protect against it?
Answer: CSRF (Cross-Site Request Forgery) is an attack that tricks the victim into submitting a malicious request. Rails includes a security feature called CSRF protection, which generates a unique token and validates that token with each POST, PUT, PATCH, and DELETE request.
5. Question: How do you manage and use different versions of Ruby in your application?
Answer: We can use RVM (Ruby Version Manager) or rbenv to manage multiple versions of Ruby. We can specify the version of Ruby that our application uses by adding this information to the .ruby-version file.
6. Question: What is ActiveRecord and what is it used for?
Answer: ActiveRecord is the M in MVC — the model — which is the layer of the system responsible for representing business data and logic. It facilitates the creation and use of objects whose data requires persistent storage to a database.
7. Question: How do you handle exceptions in Ruby on Rails?
Answer: Exceptions in Ruby on Rails can be handled using begin, rescue, ensure, and raise. For example:
#ruby
begin
# code that may raise an exception
rescue => e
# handle the exception
ensure
# this code will always run
end
8. Question: What is the difference between has_many and has_and_belongs_to_many associations in Rails?
Answer: has_many is used when one model owns the other model. has_and_belongs_to_many is used when you have a many-to-many relationship and neither model owns the other.
9. Question: How do you create a migration to add a table in Rails?
Answer: You can create a migration to add a table using the rails generate migration command. For example:
rails generate migration CreateProducts name:string description:text
10. Question: What is the purpose of yield in Rails?
Answer: yield is used in Rails layouts to render the view that corresponds to the current action. For example, if you have a layout that includes a header and footer, you can use yield to render the specific view for the action between the header and footer.