Salam.MSaif
Salam.MSaif

Reputation: 219

In Ruby on Rails, why does sometime in controller, it is plural and sometime it is singular?

class MoviesController < ApplicationController
  def index
    @movies = Movie.all
  end

  def show
    @movie = Movie.find(params[:id])
    @actors = @movie.actors
  end
end

As seen above, in the index action, @movies is used, but in the show action, @movie is used. How does one determine whether it is plural or singular?

Upvotes: 0

Views: 160

Answers (4)

Kermit
Kermit

Reputation: 5992

In the index -- you are getting all of the movies so that you can list all of the movies.

In the other controller methods -- you are typically editing a single movie.

@movies vs @movies doesn't actually matter. You could name it @banana. However, there are lots of cases like file names (model = singular, controller = plural) and Active Record relations (references) where plurality does matter

Upvotes: 0

Aashish
Aashish

Reputation: 807

Adding to @Dithanial's answer, As you may be familiar when you click on show action only that particular record is displayed. So in the below code snippet:

def show
  @movie = Movie.find(params[:id])
  @actors = @movie.actors
end

The instance variable @movie find the specific item on based of it's id and displays the content.

Upvotes: 1

Sebastian Plasschaert
Sebastian Plasschaert

Reputation: 304

In general you use plural in case of an array, and singular in case of a single object.

Upvotes: 0

Jem
Jem

Reputation: 656

Both @movies and @movie are instance variables that you choose how to define. In your example, @movies is assigned to the whole collection of Movies from your model, therefore it is conventionally assigned a plural variable. @movie is assigned to a single record, therefore it's conventionally assigned a singular variable.

You can name your instance variables whatever you want, but Rails heavily favors convention over configuration.

Upvotes: 3

Related Questions