1 / 270

Intro to Ruby on Rails

Intro to Ruby on Rails. Goals of this session Bring developers up to speed on Ruby on Rails basics SVN basics and best practices Review project governance Review mock project and assign tasks. MVC from 40,000 Feet. The model is responsible for maintaining the state of the application.

ayla
Télécharger la présentation

Intro to Ruby on Rails

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Intro to Ruby on Rails • Goals of this session • Bring developers up to speed on Ruby on Rails basics • SVN basics and best practices • Review project governance • Review mock project and assign tasks

  2. MVC from 40,000 Feet • The model is responsible for maintaining the state of the application. • Sometimes the state is permanent and will be stored outside the application,often in a database. • Sometimes transient, lasting a few iterations. • Enforces all the business rules that apply to that data.

  3. MVC cont... • The view is responsible for generating a user interface, normally based on data in the model. • The view may present the user with various ways of inputting data, BUT the view itself NEVER handles incoming data. • There may well be many views that access the same model data, often for different purposes.

  4. MVC cont... • Controllers orchestrate the application. • Controllers receive events from the outside world (normally user input), interact with the model, and display an appropriate view to the user.

  5. How does it work in Rails? • In a Rails application, incoming requests are first sent to a router. • Router works out where in the application the request should be sent and how the request itself should be parsed. • Router identifies a particular method (called an action) somewhere in the controller code. • The action might look at data in the request, might interact with the model, might cause other actions to be invoked. • The action prepares information for the view, which renders something to the user.

  6. How do I create a RoR project? • Make a project directory • From the command line - 'rails my_app' • From RadRails – new rails project • Have a look at the project structure....

  7. Logging in Rails • logger.debug(“Argh! Problems! {#var.name}”) • logger.warn(“foo”) • logger.info(“bar”) • logger.error(“foobar”) • logger.fatal(“ack!”)

  8. Using irb in Rails • Run script/console • pr = Product.find(:first) • pr.price • => 29.95 • Lets you interrogate your objects and 'play with them' in the sandbox

  9. Ruby refresher • Local vars, method params, and method names – all lowercase_with_underscores • @instance_variables_names • @@class_variable_names • :symbol – string literals that are made into constants – think of it as 'thing named' - :symbol is 'the thing named symbol'

  10. Ruby refresher cont... • Arrays = ['an','array','example','named'] • Arrays << 'arrays' – will append to the end of an array • Hashes = {:foo => 'bar', :bar => 'foo'} • Accessed same as array – Hashes[:foo] • Special notice – hashes as parameter lists...

  11. Ruby refresher cont... • Special note – ruby allows you to omit the braces on hashes as parameter calls if the has is the last parameter of the call... • What's that mean? • Redirect_to :action => 'show', :id => product.id • Is the same as • Params = {:action => 'show', :id = > product.id} • redirect_to(params)

  12. Ruby refresher... • Puts “writes to the console” • H method is used to escape html

  13. Fire up RadRails and start a project... Lets jump in!

  14. Create a model object – product • exists app/models/ • exists test/unit/ • exists test/fixtures/ • create app/models/product.rb • create test/unit/product_test.rb • create test/fixtures/products.yml • exists db/migrate • create db/migrate/001_create_products.rb

  15. 3 options when defining columns • :null => true or false • Adds not null constraint (if db supports) • :limit => size • Appends size string to column type def • :default => value • Sets default value

  16. What can migrations do? • add_column/remove_column • rename_column/rename_table • change_column • create_table/drop_table • :force=>true will drop existing table before creating • :temporary=>true creates temp table – will go away after app disconnects • :options=>”db secific options”

  17. What can migrations do? Cont.. • add_index/remove_index • Down method – deletes all rows • Primary keys – what's the scoop. • Rails assumes every table has a numeric primary key – normally called id. • Rails hates tables that don't have numeric primary keys, but doesn't care what the column name is. • Best practise? Discuss with everyone else why you'd want to use composite keys, etc before you do it. Plugins are available – but it's not fun (anectodal)

  18. When migrations attack! • Tip: if you need to manually override the the schema version that in the DB: • ruby script/runner 'ActiveRecord::Base.connection.execute( "INSERT INTO schema_info (version) VALUES(0)")' • schema_info table is created in backgroun on first migration run, and holds current migration number

  19. Run a migration • Rake migrate – runs all • Rake migrate VERSION=X • Note: schema dump file

  20. Lets play with creating migrations.. • Create 3 model objects – one for people, one for groups, one for memberships • Give each model some fields using :string data types • Run the migration to version 3 • Roll back to 0 • Run to version 3 (make mods if you care too) • Can you find the schema dump file? Have a look at it...

  21. Active Record Basics • What is Active Record? • ORM (object-relational mapping) tool supplied with Rails. • Tables map to classes, rows to objects (model objects), and columns to object attributes (accessors/mutators) • Different then others (ie. Hibernate) in that it ships with sensible defaults – minimal config.

  22. Active Record Basics cont… • When you create a subclass of ActiveRecord::Base you create an object to wrap a DB table. • Rails assumes that the name of the table is the PLURAL FORM OF THE CLASS NAME • Rails also assumes that if the name contains multiple camel-case words that the table name has underscores between the words. • Inflector does handle some irregular plurals

  23. Active Record Basics cont… • Can change default behavior – but why? • Active Record objects correspond to rows in a DB table • These objects have attributes that correspond to table columns • Notice we didn’t define these attributes in our model objects? • Active Record determines them dynamically at run

  24. Active Record Basics cont… Why’s this good? Modify migration – re-run – test. Very agile.

  25. Active Record Basics cont… Lets try playing a bit.

  26. Active Record Basics cont… Add some data to a table in your DB Open up corresponding model object in RR Generate ‘controller admin’ Open contrller object Scaffold :model_object_to_play_with Start mongrel Localhost:port/admin

  27. Active Record Basics cont… Hit localhost:port/admin Play around a bit….

  28. Active Record Basics cont… Now let’s get concrete…. Generate scaffold product admin Check force Watch your console! This is called a static scaffold. Two parameters – one for model, one for controller

  29. Active Record Basics cont… What did we just do? Took all that scaffolded code and made it ‘concrete’ Notice we didn’t overwrite our migration? You will have to be careful of model objects though – can be overwritten. Go back to site – looks the same.

  30. Active Record Basics cont… Go into your new controller object. Don’t focus on what’s in there too much, but look for a ‘show’ method. Modify your Product.find(params[:id]) to Product.find(1) Play

  31. Lets talk CRUD • What’s crud? Create Retrieve Update Delete • Lets look at how to create data in Rails • There’s a bunch of ways….lets go most manual to least…and talk about why you’d use different ones.

  32. CREATEa_product = Product.newa_product.col_name = “blah"etc…a_product.save

  33. Product.new do |o| o.col_name = “blah" # . . . o.saveend

  34. a_product = Product.new( :col_name => “blah" , :col_name2 => “blah)an_order.save- notice it takes a hash of params?

  35. product = Product.new(params[:order])Something to note with this way – could miss params if there’s no column in DB!

  36. But what about our primary key? • Connect to db – look at the table. • See the id column? • Active record automatically creates a unique key and sets the id as the row is saved. • This column was created during migration

  37. READ • Give Active Record criteria, it will return model objects containing row data. • For example: • A_product = Product.find(1) • What’s wrong with this? Assumes we know a product ID and that it exists. Will throw a RecordNotFound error. • Try it!

  38. Read cont… • # Get a list of product ids from a form • product_list = params[:product_ids] • Will return an array = number of id’s passed as params. • But what about SQL? • Here’s where it get’s interesting.

  39. READ cont… • product = Product.find(:all, :conditions => “something= ‘something' and something_else = ‘something else'" ) • Will return an array of matching rows, wrapped in a Product object. • If nothing comes back – array is empty.

  40. READ cont.. • But what about dynamic parameters? • something = params[:something] • pos = Order.find(:all, :conditions => ["name = ?" , name]) • Side note – other ways of doing this – but this is immune to sql injection attacks.

  41. something = params[:named_param] • something_else = params[:another_named] • pos = Product.find(:all, :conditions => [“something = : something and something_else = : something_else" ,{: something => something , :something_else => something_else}]) • Just uses placeholders and takes values as hash • What’s interesting about that?

More Related