1

I am reading the RailsTutorial and it is like this: in the routes.rb file we have added:

resources   :users
  • Then in the app/views/users/show.html.erb file we are using @user
  • Then in app/controllers/users_controller.rb we can still use @user
  • Then in app/views/users/show.html.erb again we can use @user

So aren't these all in different folders and classes? so @user is public? how do they see and work together? because I don't have a deep knowledge of Rails this all looks like magic to me. If someone could shed some light on internals of what's going on would be great.

user229044
  • 232,980
  • 40
  • 330
  • 338
Bohn
  • 26,091
  • 61
  • 167
  • 254
  • They're instance variables. This answer might be useful: http://stackoverflow.com/a/828519/427992 – hohner Jan 17 '13 at 21:25

3 Answers3

1

A request first touches your routes.rb file which will direct the request to the appropriate controller action.

ex. example.com/users/new will go to the UsersController new action

The new action will define instance variables which you can then access in your corresponding view (the new.html.erb in your user folder).

resource :users is a rails shortcut to create CRUD routing (http://guides.rubyonrails.org/routing.html#resources-on-the-web)

Each controller action is most likely going to have a different assignment for the @user instance variable. Read this example, http://www.tutorialspoint.com/ruby-on-rails/rails-controllers.html

More Good Reading: http://www.devarticles.com/c/a/Ruby-on-Rails/Rails-Action-Controller/1/

Kyle C
  • 4,077
  • 2
  • 31
  • 34
1

The users in your question are not all the same:

  • in routes.rb, users is not the @users / @user variable, but a symbol named :users. It could be anything else, :something, :anything, etc. It just a parameter to the "resources" method, which creates routes based on the name passed to it. So if you write, "resources :whatever", then rails will generate default routes for a class named WhateverController - if that exist, it will work
  • show.html is a view. It may use any member variable declared in it's controller / action (which is users_controller). But it is not global, if you have two controller, they can only use their own variables. Even more, two different actions (methods) in one controller can't use each other's variables, since they are not declared at that time.
  • in users_controller.rb you actually declare the @users variable which is used in the view
Dutow
  • 5,638
  • 1
  • 30
  • 40
1

the @ signifies an instance variable. The scope of a variable defines where and how it can be accessed. It would be best for you to learn about variables and their various types in general. Check this out: http://ruby.runpaint.org/variables.

OpenCoderX
  • 6,180
  • 7
  • 34
  • 61