Rails Questions first 17 - Sheet1 Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

What is the difference between include and extend in Ruby

A
  • include and extend are used to mix in modules, but they serve different purposes. include is for instance methods. When you include a module in a class, the module’s methods become instance methods of that class. On the other hand, extend is for class methods. When you extend a module, its methods become class methods of the class or object it’s being extended to. So, use include when you want to share behavior among instances and extend when you want to enhance class-level behavior.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are some of the benefits of using the Rails framework

A
  • Rails provides a powerful structure for developing web applications quickly and efficiently. It follows the DRY (Don’t Repeat Yourself) principle and Convention over Configuration, meaning you spend less time on boilerplate code. It has a strong community and a wide array of built-in libraries (gems) to handle everything from authentication to background jobs. ActiveRecord simplifies database interactions, and Rails promotes good practices like MVC architecture. It also provides tools like generators and migrations, which make it easier to develop and manage the application over time.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the purpose of before_action in Rails controllers

A
  • before_action is a filter in Rails controllers used to run a method before a particular controller action is executed. It’s typically used to set up common variables or check permissions. For example, you might use before_action to authenticate a user before allowing them to access certain actions. This helps keep your code DRY by ensuring that you don’t have to repeat the same logic across multiple actions. You can also restrict before_action to specific actions or skip it for others, giving you control over when it should be triggered.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is a Proc in Ruby, and how does it differ from a lambda

A
  • A Proc is a block of code that you can store in a variable and execute later. One key difference is that a Proc ignores argument count, meaning if you pass fewer arguments than expected, it won’t raise an error, whereas a lambda checks the number of arguments and raises an error if they don’t match. Another difference is how they handle the return keyword. A Proc will return from the enclosing method when it encounters a return, potentially exiting the method entirely. In contrast, a lambda only returns to the point where it was called, allowing the rest of the method to continue executing.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the difference between a symbol and a string in Ruby

A
  • A string is mutable, meaning it can be changed after it’s created, while a symbol is immutable and stays constant. Because of this, symbols are more memory efficient when used repeatedly in a program, since Ruby only keeps one copy of a symbol in memory. Strings, on the other hand, can have multiple copies of the same value in memory. Symbols are often used as identifiers (like in hash keys), whereas strings are used for textual data that can change or require manipulation.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are Rails migrations, and why are they useful

A
  • Migrations in Rails are a way to manage database schema changes over time. They allow you to add, remove, or modify tables and columns in a version-controlled and reversible way. Each migration represents a single change to the schema, making it easier to track and rollback changes if needed. Instead of writing raw SQL, migrations use Ruby code to define changes, which makes them database-agnostic and easy to share across different environments. This is especially useful for teams or projects where the database schema may evolve frequently.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the N+1 query problem in Rails, and how do you solve it

A

The N+1 query problem happens when your application makes one query to load a set of records (the “1” query) and then makes an additional query for each individual record to load related data (the “N” queries). For example, if you query for 10 users and each user has posts, Rails may issue one query to get all the users and then a separate query to load the posts for each user. This results in a total of 11 queries (1 + N), and as the number of users increases, the number of queries scales linearly, leading to significant performance issues.

The reason this happens is that Rails’ lazy loading behavior only fetches related records when they are accessed. So, if you loop through a collection of users and call user.posts, Rails fetches the posts for each user individually, causing the N+1 query problem.

To solve this, you can use eager loading. Rails provides methods like includes or eager_load to load associated records in one query instead of multiple. Using includes(:posts), for example, tells Rails to load the users and their associated posts in two queries—one for the users and one for all the posts. This reduces the number of queries dramatically and improves performance.

For more complex cases where you need to filter or sort the associated records, you can use joins or preload depending on the behavior you need. By addressing the N+1 query problem early on, you can prevent slowdowns in your application, especially as the database grows and the number of related records increases.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is ActiveRecord in Rails

A
  • ActiveRecord is the ORM (Object Relational Mapping) layer in Rails that connects classes to database tables. It allows you to interact with the database using Ruby code rather than writing SQL directly. Each ActiveRecord model in Rails corresponds to a table in the database, and instances of those models map to rows in that table. ActiveRecord also provides methods for querying, inserting, updating, and deleting records, as well as associations like belongs_to, has_many, and validations, which ensure data integrity.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are validations in Rails, and how do you use them

A
  • Validations in Rails are rules that ensure only valid data is saved to the database. You define them in your models to check for things like presence, uniqueness, format, and more. For example, you might use validates :email, presence: true to ensure that an email is provided before saving a user. If a validation fails, the record won’t be saved, and error messages will be available to display to the user. This helps maintain data integrity and provides a better user experience by catching issues early.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is a Rails helper, and when would you use one

A
  • Rails helpers are modules that are designed to hold methods used in your views. They help keep your views clean by moving logic out of the HTML templates and into Ruby code. Helpers are great for formatting data, building HTML snippets, or providing reusable methods for common tasks. For example, you might use a helper to format dates in a consistent way across your application or to create reusable buttons. Helpers keep your views DRY (Don’t Repeat Yourself) and improve maintainability.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is CSRF protection, and how does Rails implement it

A
  • CSRF (Cross-Site Request Forgery) is a type of attack where an attacker tricks a user into performing unwanted actions on a web application where they are authenticated. Rails protects against CSRF attacks by including a token in every form and verifying that token on submission. This token is unique to each session and ensures that the request came from the actual user, not an attacker. Rails automatically includes CSRF protection in forms and APIs unless you explicitly disable it.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is a polymorphic association in Rails

A
  • A polymorphic association allows a model to belong to more than one other model on a single association. For example, imagine you have a Comment model, and comments can be made on both Posts and Images. Instead of creating separate associations for each, you can use a polymorphic association. This way, Comment can belong to either a Post or an Image by specifying a commentable type. Polymorphic associations reduce the need for multiple join tables and make your code more flexible.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the purpose of routes in Rails

A
  • Routes in Rails map incoming HTTP requests to the appropriate controller actions. They act as the “traffic directors” of your application, ensuring that requests for URLs like /posts or /users/1 are sent to the correct controller action. Rails uses a DSL (domain-specific language) for defining routes, making it easy to create RESTful routes with methods like resources :posts, which automatically generates routes for common actions like index, show, new, create, edit, update, and destroy.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is REST, and how does Rails implement it

A
  • REST (Representational State Transfer) is an architectural style for designing networked applications. It revolves around using standard HTTP methods (GET, POST, PUT/PATCH, DELETE) to perform CRUD (Create, Read, Update, Delete) operations. Rails is built around RESTful conventions, meaning it organizes routes and controllers around these HTTP methods. For example, a GET request to /posts might be routed to the index action to list posts, while a POST request to /posts creates a new post. This convention helps keep code predictable and easy to follow.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly