Showing posts with label Rails. Show all posts
Showing posts with label Rails. Show all posts

27 September 2012

Rails application - Palindrome Validation

I wrote a ruby/rails application to validate a palindrome.  Here's the published palindrome app on Heroku:
http://glacial-river-2425.herokuapp.com/

I came up with the code in my head on the way home from work.  I came across the method .reverse in rails.  This makes checking for a palindrome pretty easy in rails.

After I came home from work I sat down, and ran IRB then input this code:
x = "racecar"
if x == x.reverse
puts "this is a palindrome"
else "this is not a palindrome"
end

It worked.  So now I just needed to put this into a published Rails application. 

I created a Rails project
Generated a Controller and a some views

in the Index view I put this code on the page:
<%=form_tag(:action =>'results') do %>

<%=text_field_tag(:word)  %>
<%= submit_tag("Submit") %>
<% end %>

Then in the controller I put this code:
  def results
    @word = params[:word]
    if @word == @word.reverse
      @palindrome = "This is a palindrome"
    else
      @palindrome = "This is NOT a palindrome"
    end
  end

Finally on the results page:
<%= @palindrome %>

So basically that simple line of code, is used to verify that a word input into the form is a palindrome or not and the results are put to a results page.


09 August 2012

First Webapp

During my lunch break today, I opened up Ruby on Rails Tutorial and walked through setting up another first time app.

So this is my 2nd app i'm working on.  I wanted to actually do something... so I decided to get something simple going and publish via Heroku.

So what's Heroku?
Heroku is this awesome cloud service, that's free, if  you're just testing your apps.  you go to heroku.com and set up an account... then you run a rails gem like: gem install heroku
and that will install it.

The idea is this:
1. you write some code
2. you commit the code locally with git commit
3. you push the commit to a remote git repo (i.e. github.com)
4. you make a call to Heroku to pick up the git repo and publish it.

I hit a few snags from the book though.  The book didn't tell me I had to change the gem sqlite3.  Heroku doesn't like it. The solution was to go into the Rails Gemfile and do something like this:
group :development, :test do
   gem "sqlite3"
end

If you don't set up a dev group like that, then it tries to compile sqlite3 on Heroku and since it has it's own db structure it will fail and error out (the error would be "an error occurred while installing sqlite3...."

So here's my webapp:
http://peaceful-castle-5270.herokuapp.com/users

Heroku makes a random name for your webapp.  That /users is the code I comitted and published. it allows users to be created based on their email address.

So how did I do it?

Well I cheated somewhat.  I used scaffolding.  In Rails there's a scaffolding option.  It will build out a structure for your application.  All I had to do, was call a Users model with the scaffolding and it built it out...
rails generate scaffold User name:string email:string

That one command did all of this.  It created the User model and set up a name and email variable as a string the user inputs.  It added in all the good stuff.

Once done, you run a rake migrate, like:
bundle exec rake db:migrate

Add this to Git: git add .
Commit with git: git commit -m "something"
Push to github (should have defined this already): git push
If you have created the Heroku space, you run:
heroku create
Publish with Heroku: git push heroku master

You're done.  Go to the url

08 August 2012

Rails: Handling Records (create, update, delete, conditions)

Creating records
There are two ways to do this but the easier way is to use the create method:
you would instantiate the class, and pass in the hash for the values you need...
Example:
subject = Subject.create(:name => "Subject name", :position => 2)

Create auto saves. 

Updating records
two ways, you could find, set and save
or use update_attribues which finds,sets and saves in one step.

the first way you would find like:
subject = Subject.find(1)
subject.name = "initial Subject"
you can verify with
subject.name
but at this point, the db hasn't been updated.
so you would run
subject.save and it would update the database.

The simpler way is to use:
First find the attribute and instantiate the object like:
subject = Subject.find(2)
Then do the update and save in one step:
subject.update_attributes(:name => "Revised Subject", :visible => true)

Deleting Records
First lets create a record to delete
Subject.create(:name => "Bad Subject")
Lets find it:
subject = Subject.find(3)
Now we can delete it with:
subject.destroy
This removes it from the database, but if you're doing thsi in Rails console, you still have access to it... you could do a
subject.name and there it is.
This hash / record exists in the console, but it's frozen, you can't modify it.  It was removed from the database.

Finding Records
To simply find a record you can use this format:
classname.find(id)
example: Subject.find(2)
this simple method will return the object, or an error

Dynamic Finders
This is useful when you want to searched based on criteria other then ID.
it is structured like this:
Classname.find_by_[indentifier]([value])
Example:
Subject.find_by_name("First Subject")
This dynamic method will return the object or nil.
This method may be depreciated at some point, due to the enhanced queires in Rails.

Find All
Subject.all
This returns an array of objects

First/Last lookup
Subject.first, Subject.last
returns an object or nil

Query Methods
This uses the ActiveRelation query methods
Example:
Subject.where(:visible => true)
The ActiveRelation query uses "where"

Conditions allow:
Strings
   Strings pass raw SQL
   This is vulnerable to SQL injection
     Malicious code could be injected

The way to handle SQL injection attacks is to escape the SQL using an Array

Array
instead of SQL, we escape it like:
["name = ? AND visible = true", "First Subject"]
This builds a safe string.

Hash
Example:
{:name => "First Subject", :visible => true}
This is fine, but it doesn't handle all SQL possibilities like Arrays.

Which to use?
Hash, until you need to use something more complex, then use the Array.  Avoid Strings.






07 August 2012

Rails: ActiveRecord and ActiveRelation

ActiveRecord
"active record" is a way of writing software (a software design pattern. )
"ActiveRecord" is a rails implementation of  active record.

Basically, it retrieves and manipulates db data as objects and NOT just as static rows.
ActiveRecords lets the objects
  • understand the structure and 
  • they know how to interact with it.  
  • They contain data but also have the ability to create, read, update and delete rows.

Examples of ActiveRecord:
To do a SQL Insert:
user = User.new
user.first_name = "Brian" 
user.save

To do a SQL Update:
user.last_name = "Warner"
user.save

To do a SQL Delete:
user.delete

ActiveRelation
This is new in Rails 3
This simplifies the generation of complex db queries.
Also, it handles the timing of queries, so these queries execute when needed.

Example of ActiveRelation:
Instead of the SQL:
select users.*, articles.*
from users
left join articles on (users.id = articles.author_id)
where users.first_name = 'Brian'
order by last_name ASC Limit 5;

it would be written like this:
users = User.where(:first_name => "Brian")
users = users.order("last_name ASC").limit(5)
users = users.include(:articles_authored)

So it shrinks down the SQL queries to some simple Ruby lines.

Rails Migrations (page 2)

Rails Migrations p2
to roll a migration back, you run rake like this:
rake db:migration VERSION=0 (0 tells it to go back to the beginning.)

if you want to target a version, or environment you would do
rake db:migration VERSION=[some version], RAILS_ENV=[some environment]

The version numbers are in the "schema_migrations" table in the db.  They are also the numeric numbers on the migration files themselves.

How it works:
By default, if you have multiple migrations (say 7 versions), and you only want version 5... you would specify the version, it will run a db migration for version 1, then version 2, all the way up to the target version.

You can also do a rake:db:migrate:up and specify the version, this will only run that one migration version.

rake db:migration:redo rolls back to the previous then up to the last one.

Rails: Migration (page 1)

Rails Migrations...
are a set of db instructions
written in Ruby
Allows you to migrate your db from one state to another
Contains both move up (to new state) and down (to a prev state)

Why use it?
Migrations keep the schema with the application code

The Migration keeps all the db schema changes... and allows sharing of schema changes.

Different users or different computers can easily set up the db to the same state

Inside the migration file it will create the table setups.  A string (i.e. t.string "first_name") will be seen as a varchar and create a column with this name.

create_table format
t.[type]
example: t.string "Name", options
Different types are: binary, boolean, date, datetime, decimal, float, integer, string, text, time.

Special Columns
created_at and updated_at are special columns in rails, you just call it out in the migration (i.e. t.imestamps) and these two columns are automatically created.

Running a migration in Rails
rake db:migrate
This runs all the migrations you have available... The output of which, looks something like this:
c:\Sites\simple_cms2>rake db:migrate
==  CreateSubjects: migrating =================================================
-- create_table(:subjects)
   -> 0.0780s
==  CreateSubjects: migrated (0.0800s) ========================================

==  CreatePages: migrating ====================================================
-- create_table(:pages)
   -> 0.0170s
-- add_index("pages", "subject_id")
   -> 0.0210s
-- add_index("pages", "permalink")
   -> 0.0770s
==  CreatePages: migrated (0.1200s) ===========================================

==  CreateSections: migrating =================================================
-- create_table(:sections)
   -> 0.0230s
-- add_index("sections", "page_id")
   -> 0.0200s
==  CreateSections: migrated (0.0450s) ========================================

==  CreateUsers: migrating ====================================================
-- create_table(:users)
   -> 0.0050s
==  CreateUsers: migrated (0.0050s) ===========================================

==  DoNothingYet: migrating ===================================================
==  DoNothingYet: migrated (0.0000s) ==========================================

After the migration, we can log into the database and check things out...
if we run the SQL:
show tables
we'll see our tables...
If we check the table we did some migration specifications with by running the SQL query:
mysql> show fields from users;



We'll get some output like this (which shows all the columns we set up in the Migration):
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| first_name | varchar(25)  | YES  |     | NULL    |                |
| last_name  | varchar(50)  | YES  |     | NULL    |                |
| email      | varchar(255) | NO   |     |         |                |
| password   | varchar(40)  | YES  |     | NULL    |                |
| created_at | datetime     | NO   |     | NULL    |                |
| updated_at | datetime     | NO   |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+

06 August 2012

Rails Routing

Routing Types are simple, default and root.




Simple
An example would be like:
                   get "demo/index"
which is a shortcut for
                   match "demo/index", :to => "demo#index"
this is saying when you get a request to go to: demo/index, to send to the controller#action (i.e. demo#index.)

Default
This separates the controller action and id with /
i.e. match ':controller(/:action(/:id(.:format)))'

Root
this is a similar match, but for the root of the application... such as:
root :to => "demo#index"
so this would say, when you hit the root of the application in a URL, it will route from this root to the controller#action.

Views and Erb's



ERB = Embedded Ruby.  it goes into the html pages and either executes or executes and outputs the result.

<% code %> - executes the code
<%= code %> - executes then outputs the code

01 August 2012

Rails Basic's Notes

So what is rails?
it's a web app framework for ruby's

That means it's a set of code libraries that can provide general functionality that can be used, and reused. It also has default values built in and flow controls.  Libraries usually don't set default values.




Rails uses MVC Architecture 
MVC architecture stands for: Model View Controler

The Model is the objects

The View is the presentation layer (what the user sees and interacts with)

The Control processes and responses to events - such as user actions

So...
Decision code goes in the controller

Data code goes in the model

Presentation code goes in the view

Rails refers to the view as the action view

Rails refers to the model as the active record

Rails refers to the model and view together as the "action pack"