I am new to ruby and a total noob in rails. My head is spinning with octothorps and cucumber and BDD after reading Michael Hartl’s tutorial.
I have experience in server side development using Archaic Java and ugly jsp/servlets. I wanna be cool and learn rails.
Need help understanding basic Rails Concepts, even after reading the book, it just doesn’t click:
- I thought I knew how to use the darn instance variables across the Models, views and controllers, but when I use them things don’t work. I need the rules for where I can use them, when and how. I kinda get how to use instance variables from the controller to the view. But Model to controller? – Clueless.
- Methods in the model, why do they need to be methods? Can i just create variables and use them in my controllers and views? How does that part work.
- um, sort of like the first question.. Variable usage in models and controllers … ??
The first thing to remember, before we even get into your questions, is that all variables, regardless of scope, are only active for the current request. You can use config values for persistence, but a global will expire at the end of a request, same as an instance variable.
Instance variables that are set in the controller are available to the view. Models only have access to variables that have been directly passed to the Class or instance. This means that if you have a
@first_namevariable, in your controller or view, you won’t be able to see it in your model. If you wanted to use it in your model, you would have to do something likeMyModelName.new( :first_name => @first_name )oran_instance_of_my_modelname.some_method_i_have_added( @first_name ).They don’t have to be methods, per se, but they almost certainly will end up being methods. Your most typical use of “variables” in a model would be the attributes. Attributes on a model are available to the instance of the model, regardless or whether it is in the view, controller, helper, or where ever. Attributes work by basically defining a setter and a getter method, behind the scenes (an attribute of
first_namewould make methodfirst_name()andfirst_name=()). These methods can even be overridden in the model, to manipulate the values prior to insertion or removal from the database. You can achieve a similar effect without the database, using http://apidock.com/ruby/Module/attr_accessor. Class methods are the same in scope, but operate on the Class, rather than a specific instance.Sorta the same as the answers for 1 and 2… 😉 Variables (but not constants) set in models must be exposed via a method to be available in the controllers and views. Nothing can be seen from a model that was not supplied explicitly. Otherwise, between the views, controllers, helpers, and whatnot, pretty much anything with an
@(or@@) in front of it is visible, and any variables without are not.