Confused on Variable

Hi, I am just working through Rails for Zombies and can’t quite get my head round this -

def create
@zombie = Zombie.create(params[:zombie])
redirect_to zombie_path(@zombie)
end

How do you know whether to use the @ symbol in front of zombie or not - for example it is not used after params but it is used after zombie_path?

Thanks

Using the @ makes it an instance variable which is required for it to be accessible in any views rendered by the controller action.

GIven only the code above, there’s no need for this as the controller never renders a view or uses @zombie anywhere outside of this method – it could be just a normal variable.

That said, a #create action will commonly re-render the new template in the case of validation errors. At that point, it would need to be an instance variable so it’s available to the template.

The tutorial may be starting out with an instance variable knowing that it will eventually add this behavior.

def create 
  @zombie = Zombie.create(params[:zombie])
  redirect_to zombie_path(@zombie)
end

The params hash params[:zombie] contains data that is passed in from a form or url by a user of your rails app.
In this case it contains the data needed to create a new Zombie.

For example, a Zombie probably has a name attribute among other attributs. So when a user wants to create a new
Zombie from a form the user will pass in ( POST ) that data. This passed-in data is stored in the params hash.

The @zombie is an instance variable.

Hi Pat and Esop,

Thank you. So if I now understand correctly basically the @zombie is required so it can be seen by the view and the :zombie is just all the information about a zombie (all its attributes) that are passed into each new zombie created. These attributes will come from the Class Zombie.

One more thing can the instance variable be called anything ie could I call it @myzombie rather than @zombie or is there a reason it has to be just @zombie for naming conventions in Rails?

Thanks again for your help

Technically you can name instance variables anything you want, but it’s a bad idea in the context of a Rails model.
Generally the name of instance variables reflect the name of the class that you are instantiating.

Take the class below for example. When I create a Zombie I create an instance of the Zombie class. It’s just a generic Zombie, a template of how to create a Zombie.

What distinguishes one Zombie from another are it’s attributes.

class Zombie < ActiveRecord::Base 
 attr_accessible :name, :bitten_on
 end   

@Esop thanks that helps