MapleCity Blog

MapleCity Blog header image 2

Rails Notes

February 1st, 2008 · No Comments

Rails Notes

Common Commands

  • Create a rails site by using the command: rails <site_name>
  • Start built-in webrick server by specifying: script/server
  • Stop the webrick server by pressing: ctr-c
  • The webrick server runs on port 3000 by default

Controller .rb

  • To generate a controller you use the generate script: script/generate controller <controller_name>
  • The generate script in the script folder is important because it allows you to generate parts of the web application such as a controller and a model in a rails friendly way.
  • May contain actions/methods which are defined as:
    • def <method_name>
      …. <statements>
      end
  • One action can call another action in your controller, you simply refer to the action by name.
  • The action either returns the last value returned or you can specify what it returns by using the return statement
  • It is recommended that every controller always have a default “index” action associated with it. This should be the first thing you do.
  • Redirecting
    • what if you wanted to redirect from one action to another in your controller?
    • you can use a rails function called redirect_to() this function is part of the action:controller library and can only be used in controllers
    • redirect_to(:controller => ’say’, :action => ‘action_name’)
    • when should you use redirect_to() versus using render()? You need to use redirect_to() after any actions that make changes to your application such as writing to a database and then if the user hits the refresh button it wont do the action again.
  • Public and Private actions
    • there might be a time when we want to have an action in our controller that we want to use but don’t want the public to be able to access. This is where private actions come into play.
    • all actions are public by default. However, if you use the keyword private above all your method definitions than anything following will be considered private. The same is true for public methods.
    • any actions that could be harmful to your application if accessed by URL should be declared private.
  • flash structure is a special hash which can be used to store information/messages as you process requests that can be used to help the end user know what has happened for example a record was successfully created, and these contents are available to the next request in this session.

View .rhtml

  • There isn’t a generator for views, most of the time you’ll create views manually with the extension .rhtml
  • Should be any valid xhtml
  • <%= … %> are the two opening and closing tags you use to include ruby in your rhtml document. Important note. the equals sign indicates that the processing will be output, but if you take out the equals sign than the ruby will still be processed but not output.
  • It’s good practice to put a minus sign at the end of your ruby statements that aren’t outputting anything so <% 1 + 1 -%> will not output a carriage return in the html code view of the page source.
  • Creating Links
    • you can either use the anchor tag of the html language or you can use the some rails built-in functions to do this for you.
    • using a rails function that is part of “action view” note that a function that is part of action view is only available to the view <%= link_to(’link text here’, :controller => ‘controller_name’, :action => ‘action_name’)%> //notice the use of the symbol for the first time :
  • Rendering
    • You can override rails sensible defaults by using the render() function. render() acts as a link between a controller action and a view, so if you use render(:controller => ’say’, :action => ‘hello’) your telling the action that contains this render function to use the hello view to render the results of the action from which it was called.
    • the render( ) function can only be used with a controller because it is only part of the action controller library.

Rails Framework

  • URL’s are mapped by rails to controllers and actions/methods in rails these are specifically referred to as “Routes” the default route is :server/:controller/:action/:id
  • In the folder structure of a rails app the only publicly accessible folder is the “public” folder… so anything that is in this folder is accessible web users. If you have special content like a flash movie you might create a .swf folder for these movies. There is also a log folder where you can refer to log files for troubleshooting purposes.
  • Don’t created needless folders and files in your public directory because rails will render them before it gets to the rails routing process.

Models

  • Models and Databases can communicate and talk with each other.
  • once you bring the model into the picture you can begin to build full blown web applications.
  • Usually you want to name a model after a database table for example database table named “albums” would have a corresponding model named “Album”
  • To generate a model you use the generate script: script/generate model <Model_name>
  • The generate script in the script folder is important because it allows you to generate parts of the web application such as a controller and a model in a rails friendly way.
  • In its default state a model is simply a class and it inherits (<) from the ActiveRecord::Base which helps to connect to databases
  • ActiveRecord like ActionController and ActionView like we’ve seen is what is able to connect to records in our databases.
  • the class name of your model needs to match the file name so for example the Animal model would have a filename of animal.rb
  • You can declare methods in a model as you would declare actions in a controller by simply using the def … end syntax.
  • to create a new instance of a model you use the “new” keyword so <instance_name>.new would create a new instance of a model.
  • all models are available at all times to all controllers.
  • always call models with a capital letter
  • after creating an instance of a model you can invoke a method by using the . (dot) notation.
  • you can create a writable attribute for a model (essentially an attribute of an object) by using the following syntax:
      • def noise=(new_noise)
        @<instance_variable> = new_noise
        end
  • there is also a shorthand way to create a writable attribute by using the following command: attr_accessor :<attribute_name>
  • every instance of a model is essentially a copy of a model
  • to make an entire instance available to the view simply assign the new instance to a instance variable in the controller.
  • you can inspect an entire object coming into your view by using the debug() function: debug(@<instance_variable>)
  • you can use an array in your controller to assign objects and then use the array in your view to access each object by looping through them.
      • for <local_reference> in @<array_instance>
        <local_reference>.<attribute_of_object>
        end
  • there is a clean way though to assign new objects to your array from within your controller without having to create a whole new object for each instance of the array:
      • @array_name = []
        <instance_name> = new.<model>
        <instance_name>.<attribute1> = <value>
        <instance_name>.<attrbute2> = <value>
        @array_name << <instance_name> //here your using the << insert method (an array method)
        REPEAT FOR MORE INSTANCES SUCH AS:
        <instance_name> = new.<model>
        <instance_name>.<attribute1> = <value>
        <instance_name>.<attrbute2> = <value>
        @array_name << <instance_name>
  • more often than not you will want to have some default values in place for attributes of your model.
    • You would create an initialize method for your model, this gets called automatically when an instance is created.
    • In the initialize method you would define all of your attributes with default values.
    • the initialize method can also be used to call other methods so it is not only used to set attributes.
  • you can ask an object directly what class it belongs to by using the .class property
  • Inheritance

    • you can make a class inherit methods and attributes from other classes you simply specify that your model inherits from another class using < <class_name>
  • Model Interaction

    • you can pass one model instance to a method of another model instance, fore example: Model.method(Model)
    • when you define your method you need to include in parenthesis the name of the local variable which will represent your passed in data/parameter for example: def <method_name>(<parameters>)… end
    • when you are calling a variable from within a model or controller you can use the self. notation to refer to the variable as if you were referring to a models attributes so for example you could say: self.<variable_name>
    • in the real world most of the time a model is directly related to a database in some way. One example of a model that isn’t related to a database would be a shopping cart.
  • Rails and Forms

    • rails has what are called “form helpers” which will help you do a lot of the repetitive tasks you would normally have to deal with. Rails has a lot of helpers built into the view.
    • some of the form helpers are:
      • to begin a form you would need to use: <%= form_tag(:controller => ‘<name>’, :action => ‘<name>’) %> // note that rails 2.0 is a little different than 1.0 with the form_tag part
      • to create a text filed you would use: <%= text_field(:<instance_name>, :<instance_attribute>) %>
      • to make a field that is a drop down for datetime you would use: <%= datetime_select(:<instance_name>, :<instance_attribute>, :start_year => <year_to_start>) %>
      • to create a submit button you would use: <%= submit_tag(”<button_label”) %>
    • you can pre-populate form fields with default data by defining the attributes of an instance in the action of the controller
    • sending an action your form parameters:
      • you’ll need to essentially trap the information and place it into your model.
      • when you create an instance of your model in the action you can pass a parameter list to this new instance, and you specifically want to pass the hash that is being returned by your form. For example:
        • @album = Album.new(params[:album]) //the .new method will try to match these form submissions with existing attributes as best it can.

Partials

  • usually this is referred to in a view as “rendering a partial”
  • a lot like a server side include in another language
  • to render a partial you would use the following syntax: render :partial => ‘<name_of_partial>’
  • it is a good practice to always put the underscore in front of a partial file to notate that it is in fact a partial.

Validation


  • when you create a new record with the .save method of your model it may be possible that the save fails.
  • it is the most efficient method of working if you can try to save the model instance and in the process of saving the instance can preform its own checks/validations to make sure the data is acceptable and based on that give the user feedback.
  • if you can try to place all your validations inside the model rather than inside the controller which will call these each and ever time you try to use them it will be more closely following the DRY principle
  • it is a good idea to provide a view helper method to display any errors that might have occurred. One method that you can call is named error_messages_for(:<symbol_for_model_instance>)
  • how to create some validations:
    • open your model for which you want to validate
    • provide a validation method to your model a couple of common validation methods are:
      • validates_presence_of :<attribute_name>, :<attribute_name>, :etc…, :etc… //basically this method makes sure that the provided attributes exist before it tries to save or update a database record
      • validates_length_of :<attribute_name>, minimum => <number_of_chars> //attribute is at least a certain number of characters long
      • validates_uniqueness_of :<attribute_name> //will check that the value of the attribute is a completely unique value so for example the name Warren couldn’t be added if that name already existed.
  • There is a lot more to validation than what has been written above… refer to other documentation for more information
Sphere: Related Content

Tags: Programming


0 responses so far ↓

  • There are no comments yet...Kick things off by filling out the form below.

Leave a Comment