The Rails Guides: Views and Controllers Flashcards

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

How does the Controller handle requests in Rails?

A

The Controller orchestrates the handling of requests in Rails, typically delegating heavy code execution to the Model. It then manages the response generation process, handing off to the View when it’s time to send a response back to the user.

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

What are the three ways to create an HTTP response from a controller in Rails?

A

From a controller, you can create an HTTP response by calling render to generate a full response, redirect_to to send a redirect status code, or head to create a response consisting solely of HTTP headers.

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

Explain the concept of “convention over configuration” in the context of default rendering in Rails.

A

“Convention over configuration” in Rails means that controllers automatically render views with names corresponding to valid routes by default, reducing the need for explicit rendering calls.

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

How does Rails automatically determine which view to render in a controller action?

A

Rails automatically renders a view with a name corresponding to the controller action unless explicitly specified otherwise. For example, the index action in the BooksController renders the index.html.erb view by default.

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

What happens if you don’t explicitly call render at the end of a controller action in Rails?

A

If you don’t explicitly call render at the end of a controller action in Rails, Rails will automatically look for the corresponding view template based on the action name.

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

What is the purpose of the render method in Rails controllers?

A

The render method in Rails controllers is used to render views, allowing controllers to generate content for use by a browser.

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

How can you render the view corresponding to a different template within the same controller?

A

You can render the view corresponding to a different template within the same controller by using the render method with the name of the view.

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

Can you render a template from an entirely different controller using the render method?

A

Yes, you can render a template from an entirely different controller using the render method by specifying the full path relative to app/views.

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

What are some options available for customizing the behavior of the render method?

A

Some options available for customizing the behavior of the render method include specifying content type, layout, location, status, formats, and variants.

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

What does the render :inline option do in Rails controllers?

A

The render :inline option in Rails controllers allows you to supply ERB directly as part of the method call.

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

When would you use the render plain: option in Rails?

A

The render plain: option in Rails is used to send plain text back to the browser, useful for responding to Ajax or web service requests.

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

How can you render an HTML string back to the browser in Rails?

A

You can render an HTML string back to the browser in Rails using the render html: option.

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

What is the purpose of rendering JSON in Rails, and how is it achieved?

A

Rails supports rendering JSON responses for use by Ajax libraries. This is achieved using the render json: option.

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

How does Rails support rendering XML responses?

A

Rails has built-in support for converting objects to XML and rendering that XML back to the caller using the render xml: option.

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

Can you render vanilla JavaScript using Rails? If so, how?

A

Yes, Rails can render vanilla JavaScript using the render js: option.

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

What does the render body: option do in Rails controllers?

A

The render body: option in Rails controllers sends a raw content back to the browser without setting any content type.

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

How can you render a raw file in Rails from an absolute path?

A

You can render a raw file in Rails from an absolute path using the render file: option.

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

What are the options available for specifying layouts in Rails?

A

Options available for specifying layouts in Rails include specifying layout files directly or deferring the choice of layout until runtime.

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

How can you defer the choice of layout until a request is processed in Rails?

A

You can defer the choice of layout until a request is processed in Rails by using a symbol or an inline method like a Proc.

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

What are conditional layouts in Rails, and how are they specified?

A

Conditional layouts in Rails are specified using the :only and :except options, which take method names corresponding to controller actions.

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

How does layout inheritance work in Rails controllers?

A

Layout inheritance in Rails controllers means that layout declarations cascade downward in the hierarchy, and more specific layout declarations always override more general ones.

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

How does template inheritance work in Rails controllers?

A

Template inheritance in Rails controllers means that if a template or partial is not found in the conventional path, the controller will look for a template or partial to render in its inheritance chain.

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

What can cause “double render errors” in Rails, and how can they be avoided?

A

“Double render errors” in Rails are caused by having more than one call to render or redirect in a single code path. They can be avoided by ensuring there’s only one call to render or redirect per action, possibly using return to exit early from the action.

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

What is the purpose of the redirect_to method in Rails?

A

The redirect_to method in Rails tells the browser to send a new request for a different URL.

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

How does redirect_back differ from redirect_to in Rails?

A

redirect_back returns the user to the page they just came from by pulling the location from the HTTP_REFERER header, while redirect_to sends the browser to a specified URL.

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

What happens to method execution after calling redirect_to or redirect_back in Rails?

A

Method execution continues after calling redirect_to or redirect_back in Rails. Statements occurring after them will be executed unless halted by an explicit return or some other halting mechanism.

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

How can you specify a different HTTP status code when using redirect_to in Rails?

A

You can specify a different HTTP status code, such as 301 for a permanent redirect, by using the :status option with the redirect_to method.

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

What misconception about redirect_to do inexperienced developers often have?

A

Inexperienced developers sometimes think of redirect_to as a “goto” command, moving execution from one place to another in Rails code. However, redirect_to actually stops the code execution and waits for a new request from the browser, sending back an HTTP 302 status code with the new request URL.

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

How can you handle scenarios where a required variable is nil using redirect_to in Rails?

A

If a required variable is nil, you can use redirect_to to redirect to another action instead of rendering. This ensures that the browser makes a fresh request and the necessary variables are set up properly.

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

What is the purpose of the head method in Rails?

A

The head method in Rails is used to send responses with only headers to the browser, allowing you to specify an HTTP status code and additional header options.

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

How can you use the head method to return an error header in Rails?

A

You can use the head method with a specific status code, such as :bad_request, to return an error header to the browser in Rails.

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

What are some scenarios where you might use partials in Rails views?

A

Partials in Rails views are useful for breaking down the rendering process into manageable chunks, reducing duplication, and organizing reusable pieces of code.

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

How do you pass local variables to partials in Rails?

A

Local variables can be passed to partials in Rails using the locals option with the render method or by using the as option when rendering a collection.

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

What is the main form helper in Rails, and how is it typically used?

A

The main form helper in Rails is form_with. When called without arguments, it generates a form tag that submits to the current page via POST method.

35
Q

How can you create a basic search form using form_with?

A

You can create a basic search form by specifying the URL and method (GET) with form_with, along with input fields for the search query and a submit button.

36
Q

What are some commonly used form elements provided by the form builder object in Rails?

A

Some commonly used form elements include text fields, checkboxes, radio buttons, text areas, hidden fields, password fields, number fields, date and time fields, and more.

37
Q

How are checkboxes and radio buttons generated using the form builder in Rails?

A

Checkboxes and radio buttons are generated using form.check_box and form.radio_button methods, respectively. They take the input name as the first parameter and optional label as the second parameter.

38
Q

How can you bind a form to a model object in Rails?

A

You can bind a form to a model object by specifying the model argument in form_with. This automatically populates form fields with values from the model and sets the form action to an appropriate route for the model.

39
Q

What is the significance of the _method parameter in Rails forms?

A

The _method parameter allows Rails to emulate HTTP methods other than GET and POST by overriding the actual method used for form submission. This is useful for making PATCH, PUT, and DELETE requests.

40
Q

How can you create a select box in Rails, and what are some advanced features it supports?

A

You can create a select box using the form.select method in Rails, which supports options like default selection, option groups, and binding to model attributes.

41
Q

How can you leverage time zone and country select functionalities in Rails forms?

A

To select time zones, you can use the time_zone_select helper, which generates options from a list of pre-defined time zones. For country selection, you can use the country_select plugin, which provides similar functionality.

42
Q

What are alternative options provided by Rails if HTML5 date and time inputs are not used?

A

Rails provides alternative date and time form helpers that render plain select boxes for each temporal component (e.g., year, month, day, etc).

43
Q

How does Rails handle the submission of form data when using select boxes for date and time inputs?

A

When the form is submitted, Rails assembles specially-named values (e.g., “birth_date(1i)”) into a full date or time based on the declared type of the model attribute. These values are then accessible via the params hash.

44
Q

What are the helpers provided by Rails for rendering select boxes for individual temporal components?

A

Rails provides helpers like select_year, select_month, select_day, select_hour, select_minute, and select_second for rendering select boxes for individual temporal components.

45
Q

How does the collection_select helper differ from the select helper in terms of specifying choices?

A

In collection_select, the value method is specified first followed by the text label method, which is opposite to the order used in the select helper.

46
Q

Explain the purpose of the accepts_nested_attributes_for method in Rails models.

A

The accepts_nested_attributes_for method in Rails models allows creating, updating, and optionally destroying associated records through the parent record’s form.

47
Q

What is the significance of the _destroy attribute in nested forms?

A

The _destroy attribute, when set to a truthy value (e.g., true), indicates that the associated record should be destroyed upon form submission, allowing users to remove associated objects.

48
Q

How can you prevent empty records from being created in nested forms?

A

You can use the :reject_if option with accepts_nested_attributes_for to specify a proc that determines whether to build an associated object based on the submitted attributes.

49
Q

What is the purpose of tag helpers like check_box_tag in Rails?

A

Tag helpers like check_box_tag are used to render form fields outside the context of a form builder, providing a convenient way to generate form elements.

50
Q

What is the role of a controller in the MVC architecture?

A

In the MVC architecture, a controller acts as the middleman between models and views. It receives requests, interacts with models to fetch or save data, and then uses views to generate appropriate output for the user.

51
Q

What is the naming convention recommended for controllers in Rails?

A

The naming convention suggests pluralization of the last word in the controller’s name. For example, “ClientsController” is preferred over “ClientController.”

52
Q

How does Rails determine which controller action to run for a given request?

A

Rails determines the controller action based on the routing. When a request is received, the routing system determines the appropriate controller and action to handle it.

53
Q

What types of parameters can be accessed in Rails controller actions?

A

Rails controller actions can access both query string parameters and POST data parameters. These parameters are available in the params hash in the controller.

54
Q

How can nested parameters be permitted in Rails controller strong parameters?

A

Nested parameters can be permitted by using the permit method with nested hashes or arrays. For example, params.permit(:name, { emails: [] }) permits the name attribute and an array of emails.

55
Q

What is the purpose of the session in a Rails application?

A

The session in a Rails application allows you to store small amounts of data persistently between requests for each user. It is commonly used for tasks like user authentication and passing error messages between requests.

56
Q

How can you access the session in a Rails controller?

A

You can access the session in a Rails controller through the session instance method. This allows you to read and write data to the session.

57
Q

What is the difference between flash and flash.now in Rails?

A

The flash hash stores data that is available to the next request, while flash.now stores data that is only available in the current request. This is useful for displaying error messages immediately after a failed action.

58
Q

What are cookies in Rails, and how are they accessed?

A

Cookies in Rails are small amounts of data stored on the client’s browser. They are accessed using the cookies method, which works similar to a hash.

59
Q

How can you auto-fill a form field with a stored cookie value in Rails?

A

To auto-fill a form field with a stored cookie value in Rails, you can use code similar to this:

60
Q

How can you delete a cookie in Rails?

A

To delete a cookie in Rails, you can use the cookies.delete(:key) method.

61
Q

What are signed and encrypted cookie jars in Rails, and how do they differ?

A

Signed cookie jars append a cryptographic signature on cookie values to protect integrity, while encrypted cookie jars encrypt the values in addition to signing them, preventing them from being read by the end-user.

62
Q

What is the default serializer for cookies in Rails, and what are its limitations?

A

The default serializer for cookies in Rails is :json. Its limitations include limited support for round-tripping Ruby objects, such as Date, Time, and Symbol objects, which will be serialized and deserialized into Strings.

63
Q

How can you set a cookie with an expiration date in Rails?

A

You can set a cookie with an expiration date in Rails using code similar to this:

64
Q

What are filters in Rails, and how do they work?

A

Filters in Rails are methods that are run “before”, “after”, or “around” a controller action. They are inherited, so if set on ApplicationController, they will be run on every controller in the application.

65
Q

How can you prevent a filter from running before specific actions in Rails?

A

You can prevent a filter from running before specific actions in Rails using the skip_before_action method, specifying the actions to skip the filter for.

66
Q

What are “after” and “around” filters in Rails, and how do they differ from “before” filters?

A

“After” filters are run after an action has been executed, while “around” filters can run before and after an action. They differ from “before” filters in terms of when they are executed in relation to the action.

67
Q

How can you use blocks directly with action methods in Rails?

A

You can use blocks directly with action methods in Rails by passing a block to the *_action methods. The block receives the controller as an argument.

68
Q

What is HTTP Basic Authentication in Rails, and how can you implement it?

A

HTTP Basic Authentication is an authentication scheme supported by most browsers. In Rails, you can implement it using the http_basic_authenticate_with method.

69
Q

How can you send a file to the user instead of rendering an HTML page in Rails?

A

You can send a file to the user instead of rendering an HTML page in Rails using the send_file method.

70
Q

What is the purpose of log filtering in Rails?

A

Log filtering in Rails is used to filter out sensitive information from log files, such as passwords or redirect URLs.

71
Q

How can you force communication to your controller to be only via HTTPS in Rails?

A

You can force communication to your controller to be only via HTTPS in Rails by enabling the ActionDispatch::SSL middleware via the config.force_ssl option in your environment configuration.

72
Q

What is the purpose of the built-in health check endpoint in Rails?

A

The purpose of the built-in health check endpoint in Rails is to provide a simple way to check if the application has booted successfully and is running without exceptions.

73
Q

What is the purpose of the Rails router?

A

The purpose of the Rails router is to recognize URLs and dispatch them to a controller’s action or to a Rack application. Additionally, it can generate paths and URLs, reducing the need to hardcode strings in views.

74
Q

How does the Rails router connect URLs to code?

A

When an incoming request is received, such as “GET /patients/17”, the Rails router matches it to a controller action based on the defined routes. For example, if the route is “get ‘/patients/:id’, to: ‘patients#show’”, the request is dispatched to the “show” action of the “patients” controller with the appropriate parameters.

75
Q

How does Rails generate paths and URLs from code?

A

Rails can generate paths and URLs by defining routes with specific names using the “as” option. For instance, if the route is “get ‘/patients/:id’, to: ‘patients#show’, as: ‘patient’”, and in the controller you have “@patient = Patient.find(params[:id])”, then in the view, you can use “patient_path(@patient)” to generate the path “/patients/17”.

76
Q

What configuration file contains the routes for a Rails application?

A

The routes for a Rails application are typically defined in the “config/routes.rb” file.

77
Q

What does resource routing in Rails allow you to do?

A

Resource routing in Rails allows you to quickly declare all common routes for a given resourceful controller, including index, show, new, edit, create, update, and destroy actions.

78
Q

How does Rails handle CRUD operations with resourceful routes?

A

In Rails, each resourceful route maps HTTP verbs and URLs to controller actions, corresponding to specific CRUD operations in a database. For example, the route “resources :photos” creates seven different routes mapping to the Photos controller for actions like index, show, create, update, and delete.

79
Q

What are some advantages of using path and URL helpers in Rails?

A

Using path and URL helpers in Rails reduces the brittleness of views and makes code easier to understand. It also helps avoid hardcoding URLs in views, which can lead to cleaner and more maintainable code.

80
Q

How can you add additional routes to a resource in Rails?

A

In Rails, you can add additional routes to a resource using member routes for actions that apply to individual members of the resource, or collection routes for actions that apply to the entire collection. These routes can be defined within a member or collection block in the resources declaration.

81
Q

How can you define defaults for routes in Rails?

A

Defaults for routes in Rails can be defined by supplying a hash for the :defaults option. For example:

82
Q

What are three examples of non-resourceful routes in Rails?

A

Non-resourceful routes in Rails provide flexibility for mapping arbitrary URLs to actions. Three examples include:
Bound Parameters: Mapping routes with optional parameters, such as photos(/:id) to photos#display.
Dynamic Segments: Defining routes with variable segments accessible in the action’s params, like photos/:id/:user_id to photos#show.
Static Segments: Specifying fixed segments in routes, such as photos/:id/with_user/:user_id to photos#show.

83
Q

How can you set up dynamic segments within a regular route?

A

Dynamic segments in a regular route can be set up by defining a route with variable segments. For example:

Incoming paths like /photos/1/2 will be dispatched to the show action of the PhotosController, with params[:id] as “1” and params[:user_id] as “2”.

84
Q

What is the purpose of using static segments in route creation?

A

Static segments in route creation serve to define fixed parts of a route without using dynamic parameters.

This route responds to paths like /photos/1/with_user/2, where params would be { controller: ‘photos’, action: ‘show’, id: ‘1’, user_id: ‘2’ }.