Associations INFO 2310: Topics in Web Design and Programming.

Slides:



Advertisements
Similar presentations
JQuery MessageBoard. Lets use jQuery and AJAX in combination with a database to update and retrieve information without refreshing the page. Here we will.
Advertisements

The Librarian Web Page Carol Wolf CS396X. Create new controller  To create a new controller that can manage more than just books, type ruby script/generate.
Version Control System (Sub)Version Control (SVN).
Trestle Generator Industrial-strength scaffolding for Ruby on Rails web application development.
JavaScript and Ajax INFO 2310: Topics in Web Design and Programming.
CS 142 Lecture Notes: Rails ActiveRecordSlide 1 Model for Student Table SELECT * FROM students; | id | name.
Creating a wiki blog. Run apps that come with instant rails distribution select I /rails applications/open ruby console window Cd to cookbook or typo.
How to Establish a Blog. What is a Blog A blog is a collection of informational articles/ideas intended to update a viewer on new information associated.
Ruby on Rails Creating a Rails Application Carol E Wolf CS396X.
Creating Web Page Forms
Intro to Rails INFO 2310: Topics in Web Design and Programming.
Working with SharePoint Document Libraries. What are document libraries? Document libraries are collections of files that you can share with team members.
Sharepoint Portal Server Basics. Introduction Sharepoint server belongs to Microsoft family of servers Integrated suite of server capabilities Hosted.
Creating a Web Page HTML, FrontPage, Word, Composer.
Web Development 311 Fall : Fall Why web pages? Most companies have intranets, extranets, and web sites Content can be changed quickly and.
Ruby on Rails: An Introduction JA-SIG Summer Conference 2007 Michael Irion The University of Tulsa.
Ruby on Rails. What is Ruby on Rails? Ruby on Rails is an open source full-stack web framework. It is an alternative to PHP/MySQL. It can render templates,
MVC in Trax.
Ruby on Rails CSCI 6314 David Gaspar Jennifer Garcia Avila.
Authentication/Authorization INFO 2310: Topics in Web Design and Programming.
Rails and Grails. To get started Make sure you have java installed You can get the sdk and jre at:
ACM Web Development Workshop - PHP By Luis Torres.
1 Dr Alexiei Dingli Web Science Stream Models, Views and Controllers.
UC Berkeley Hello Rails. Review: MVC Goal: separate organization of data (model) from UI & presentation (view) by introducing controller –mediates user.
BIT 286: Web Applications Lecture 04 : Thursday, January 15, 2015 ASP.Net MVC - Models.
How KeePass password safe can save you time and energy
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
Bill's Amazing Content Rotator jQuery Content Rotator.
1 Dr Alexiei Dingli Web Science Stream Advanced ROR.
Ruby on Rails Your first app. Rails files app/ Contains the controllers, models, views and assets for your application. You’ll focus on this folder for.
Installing and Using MySQL and phpMyAdmin. Last Time... Installing Apache server Installing PHP Running basic PHP scripts on the server Not necessary.
Ruby on Rails CSE 190M, Spring 2009 Week 6. Overview How to use a database Demo creating a blog application on Rails Explain how the application works.
Patrick Bailey, MS IDIS110 Dreamweaver Setup. IDIS110 - RIT After you start Dreamweaver On the first time, if you are asked, select “Design Mode” Otherwise,
© Copyright IBM Corporation 2007 AP/Americas April 15-18, 2007 Anaheim, California Introduction to RubyOnRails - a J2EE replacement? Russell Scheerer –
Forms and Server Side Includes. What are Forms? Forms are used to get user input We’ve all used them before. For example, ever had to sign up for courses.
1 Dr Alexiei Dingli Web Science Stream A ROR Blog.
Photo Gallery INFO 2310: Topics in Web Design and Programming.
CS 142 Lecture Notes: Rails ActiveRecordSlide 1 Model for Student Table SELECT * FROM students; | id | name.
Ruby on Rails: Databases. Rails Database Familiar Table Concept Naming convention – lower case, plural (i.e. tweets) How to Access (find), Update, Delete.
Diagnostic Pathfinder for Instructors. Diagnostic Pathfinder Local File vs. Database Normal operations Expert operations Admin operations.
1 What to do before class starts??? Download the sample database from the k: drive to the u: drive or to your flash drive. The database is named “FormBelmont.accdb”
1 Dr Alexiei Dingli Web Science Stream A ROR Twitter.
Publishing Your Web Pages Ann Emmanuel SIUE Web Administrator
InfoBox A Personal Information Manager Built with Ruby on Rails Dustin Martin.
Access Forms and Queries. Entering Data in Your Table  You can add data to your table in Datasheet view, by typing in the columns and rows.  This.
Routes & REST & URL-helpers & validations & filters
1 Dr Alexiei Dingli Web Science Stream Web We’ll implement a voting mechanism Using AJAX Web 2.0.
Chapter 15 © 2013 by Pearson Overview of Rails - Rails is a development framework for Web-based applications - Based on MVC architecture for applications.
1 Migration. 2 What’s Migration? Migration –Isolates database differences Allows you to write schema updates without worries about differences –Helps.
L.T.E :: Learning Through Experimenting Using google-svn for MtM Docs Development Denis Thibault Version 3.2 Mar 12 th, 2009.
® IBM Software Group © 2006 IBM Corporation JSF Rich Text Area Component This Learning Module describes the use of the JSF Rich Text Area component – for.
M1G Introduction to Programming 2 3. Creating Classes: Room and Item.
Introduction to Ruby&Rails Yuri Veremeyenko Monica Verma.
GOOGLE GROUPS TRAINING How to use the internet to make the Own It! project teams as efficient and successful as possible.
Adding Data to a Database Table Carol Wolf Computer Science.
Rails and routing INFO 2310: Topics in Web Design and Programming.
CS 160 and CMPE/SE 131 Software Engineering February 9 Class Meeting Department of Computer Science Department of Computer Engineering San José State University.
Migrations Carol Wolf CS 396X. ISBNTitleAuthorImage EmmaAustenemma.jpg Oliver TwistDickenstwist.jpg HamletShakespearehamlet.jpg.
1 Project 7: Looping. Project 7 For this project you will produce two Java programs. The requirements for each program will be described separately on.
Access Queries and Forms. Adding a New Field  To insert a field after you have saved your table, open Access, and open the table  It is easier to add.
Ruby on Rails. Web Framework for Ruby Designed to make it easier to develop, deploy, and maintain web applications Design with Model-View-Controller –almost.
Entity Framework Database Connection with ASP Notes from started/getting-started-with-ef-using-mvc/creating-an-
Advanced Migration By Aye Mon Tun.  To change database schema in consistent and easy way  In ruby code Migration? 11/25/2013 2Web Application Engineering.
Your current Moodle 1.9 Minimum Requirements Ability to do a TEST RUN! Upgrading Moodle to Version 2 By Ramzan Jabbar Doncaster College for the Deaf By.
1 Adding a Model. We have created an MVC web app project Added a controller class. Added a view class. Next we will add some classes for managing movies.
Submitting Requests to IT
MVC Framework, in general.
Agile Web Development with Ruby and Rails
Model for Student Table
Building Web Applications
Presentation transcript:

Associations INFO 2310: Topics in Web Design and Programming

Most of today How do we add a related model to already existing models? But first…

Using an IDE

For your convenience, we’ve had Komodo Edit 4.4 installed on all the lab machines. It makes navigating all your files a bit easier. For Mac users, everyone I know seems to swear by TextMate.

To make a ‘project’ from your blog, do “File/New Project From Template”. Select the Ruby on Rails template (from “Common”). Name your project something (“blog”, maybe) and select as its directory the current directory for your blog. Komodo Edit is smart enough to realize that all the files in that directory belong to your project.

Some nice things You can run some Rails commands from inside the editor. With your project open, look inside the folder ‘Rails Tools’. Try ‘Run/run server’.

Partials

With ‘partials’, we can create ‘partial’ views that can be rendered inside other views. A bit like a PHP ‘include’. The file name of a partial is prefixed with an ‘_’.

Let’s try one… Notice that app/views/posts/new.html.erb and app/views/posts/edit.html.erb are almost identical. Let’s capture the common part in a partial.

_form.html.erb Create a new file ‘app/views/posts/_form.html.erb’. Copy the following from ‘app/views/posts/edit.html.erb’ into ‘_form’:

Now edit blog/app/views/posts/edit.html.erb by replacing the removed code with: ‘form’ %> and the same for blog/app/views/posts/new.html.erb. Now try the blog…

Problem… The submit button says ‘Create’ for both entering a new entry and editing an old one. We can solve this by passing in local variables to each…

Edits _form.html.erb; change f.submit line to new.html.erb; change render line to 'form', :locals => {:action => 'Create'} %> edit.html.erb; change render line to 'form', :locals => {:action => 'Update'} %>

Adding a model

Now we’ll get down to the business of adding another model to our site. We need to: Create the model and any associations with other models. Create the associated controller. Create the associated views. Update the database. Update the routes.

Scaffolding We can get a lot of this done via scaffolding; this will set up the files to create the model/controllers/views, just like we did last time for the posts model. Go to your blog directory, and enter “ ruby script/generate scaffold comment body:text post_id:integer ”. (Through Komodo: Ruby Tools/Generate/scaffold).

Adding a table Rails lets us modify our DB through migrations: Ruby code that explains the changes to make to our DB and then how to undo them.

The migration This creates a file in db/migrate called 2008xxxxxxx_create_comments.rb. You’ll see another file in that directory, 2008xxxxx_create_posts.rb, which created the posts DB.

create_comments class CreateComments < ActiveRecord::Migration def self.up create_table :comments do |t| t.integer :post_id t.text :body t.timestamps end def self.down drop_table :comments end

Migrating To actually get this to run and create the table, we need to run ‘ rake db:migrate ’. (Through Komodo: Rails Tools/Migrate/db:migrate). We can use migrations to move back and forth between various versions of the DB if needed.

Users OK, let’s scaffold out another model (and views and controllers) for users. Users will have a name, password, and , all strings. You do it, this time… Be sure to run the migration to create the table.

Associations

We now want to be able to tell the models about the various connections that they have with each other.

ER Diagram

We can have these relationships reflected in the models by adding information to the model files.

Open up the post model in app/models/post.rb. We can tell the post about associated comments. class Post < ActiveRecord::Base has_many :comments validates_presence_of :title, :body validates_format_of :title, :with => /^[\w\d]+$/ end Because each comment has a post_id, Rails can automatically associate each comment with a particular post.

We can also tell the model how to associate itself with another model (if we don’t follow the defaults). class Post < ActiveRecord::Base has_many :comments belongs_to :author, :class_name => "User", :foreign_key => "user_id" validates_presence_of :title, :body validates_format_of :title, :with => /^[\w\d]+$/ end

Let’s now enter the associations for other models as well. class Comment < ActiveRecord::Base belongs_to :post end class User < ActiveRecord::Base has_many :posts end

The association of the Post model with the User model isn’t going to work quite yet; why not? class Post < ActiveRecord::Base has_many :comments belongs_to :author, :class_name => "User", :foreign_key => "user_id" validates_presence_of :title, :body validates_format_of :title, :with => /^[\w\d]+$/ end

We need to add a column to the posts DB that tells us the user_id of the author of the post. We can do this through a migration. Type ‘ ruby script/generate migration add_user_id ’ (or Rails Tools/Generators/migration in Komodo).

In db/migrations/2008xxxx_add_user_id, create a migration to add a column to the posts DB as follows: class AddUserId < ActiveRecord::Migration def self.up add_column :posts, :user_id, :integer end def self.down remove_column :posts, :user_id end Go ahead and run the migration (you do remember how to do that, right?)

Now you can go ahead and add comments and users by starting up the web server ( ruby script/server ) and navigating to and

This doesn’t let us enter/edit the user_ids associated with the posts because the associated views with posts are still the same. We can fix this by updating the views.

In app/views/posts/_form.html.erb, add two lines to allow the user id to be input/edited. Go ahead and enter some users, some comments and posts associated with those users.

Now we can see how the associations work by starting up the console ( ruby script/console = => “New post through association”, :body => “It knows the user who made it!”)

Partial collections

This is a little unsatisfying so far. Every post has an associated set of comments, but we’re entering them and editing them as independent entities linked by a post_id. We like it to work like a real blog.

One idea: we want the URL posts/3 to list all the comments associated with post #3. We can do this by editing the associated view and having it display the associated comments

We could loop through these with a for loop, but instead let’s use partials again. Create a file app/views/comments/_comment.html.erb. Put in it something like this:

Now we can render all the comments by adding this line to app/views/posts/show.html.erb. “/comments/comment", :collection %>

Nested resources

In fact, it really doesn’t make sense for comments to be separate from posts; we shouldn’t be able to create a separate comment #4 via a URL comments/4. We really want every comment connected to a post; the URLs for comments should be posts/2/comments/4.

We can do this by updating our routing table to declare that comments are a resource nested inside posts.

Get config/routes.rb. Remove the line map.resources :comments Modify the line map.resources :posts to map.resources :posts do |post| post.resources :comments end

We can see what the new routes are by typing ‘ rake routes ’.

We’d like someone to be able to add a comment to a post. In app/views/posts/show.html.erb, we can add the line | before the links to Edit and Back.

This breaks when we actually try to enter a new comment. A few things to fix: The view The comments controller

new.html.erb Edit app/views/comments/new.html.erb to: New comment {:action => :create} do |f| %>

Comments controller For almost everything we want to do in the comments controller, we’re going to want the post associated with the comment. We can set up a call to make sure we get it each time.

before_filter At the top of the comments controller we add before_filter :grab_post This gets called before each action. At the bottom we define this method private def = Post.find(params[:post_id]) end

Comments controller In fact, we then should redefine all the actions in the comments controller in (app/controllers/comments.rb). See code snippets for the entire file.

class CommentsController < ApplicationController before_filter :grab_post def = Comment.find(:all) end def = Comment.find(params[:id]) end def = Comment.new end def end def =Comment.new(params[:comment]) if redirect_to else render :action => :new end def redirect_to else render :action => :edit end def destroy redirect_to end private def = Post.find(params[:post_id]) end

To dos.. There’s still plenty of work to do in fixing up the views and controllers to get them to do what you want… Next time: Adding authentication/authorization from users