Sie sind auf Seite 1von 11

Laptop Shop Tutorial 1 – Setup Stage

1. Open a command prompt (terminal window) and change directory (using the
“cd” command) to where you want to create your new project. For example:

C:\> cd C:\src

2. Create new project:

C:\src> rails new laptop_shop1

3. Change directory to the newly created Rails project directory “cd


laptop_shop1”. Make sure all necessary gems are installed on your
machine:

C:\src\laptop_shop1> bundle install

4. Create your empty databases:

C:\src\laptop_shop1> rake db:create

5. Start your Rails project server

C:\src\laptop_shop1> rails server

6. Open your browser and go to the root/homepage of the application you’ve


just created. Make sure the welcome aboard page is displayed successfully.
7. Now use the rails generate scaffold generator to generate scaffold
for our product model. This will generate a migration with the three attribute
we specified, a model, a controller (with code for all the 7 basic actions
generated) and some helper and test files.

C:\src\laptop_shop1> rails generate scaffold Product


name:string description:text price:float

8. Run the migration to create the table for Product in the database:

C:\src\laptop_shop1> rake db:migrate


(in C:/src/laptop_shop1)
== CreateProducts: migrating =======================
-- create_table(:products)
-> 0.0009s
== CreateProducts: migrated (0.0010s) ==============

9. Now lets try going to the products index page in the browser. Because we
used the scaffold generator which generates a basic controller and adds a line
to the config\routes.rb, we don’t have to setup the route ourselves we can
just go to:

http://127.0.0.1:3000/products

10. Once that’s working, lets set the products#index page as our root/homepage.
We do this by adding/changing a line in the routes.rb file. Open routes.rb and
go to line 51, you should see some commented out lines like this:

# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
# root :to => "welcome#index"

Uncomment the last line (which begins with: “root :to =>”) and change
the value being set to “products#index”. This secton will now read:

# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
root :to => "products#index"

11. You’ll need to restart your rails server for it to pick up this change.
(Shutdown the server by going to the terminal/command window that is
running the server and press “Ctrl + c” ……. then restart by typing
“rails server” again). Remember to delete the default rails “Welcome
Aboard” page too, otherwise this will continue to display as the root page.
12. At this stage we have a basic application that going to the products listing
page (which is the index action of our products controller …….
“products#index”). We can create, read, update and delete products from
here. When setting up a new project in development mode it can sometimes
be useful to have some “seed” data in our application to represent sample
products that we can begin working with. This sample/seed data can be
created by hand ……. but remembering that one of the principles of Rails is
Don’t Repeat Yourself (DRY) it probably has a nice time saving way to set up
sample products ……. and it does.

13. Go to the laptop_shop1\db\seeds.rb file in your project and paste the


following code into the end of the file:

#name description price


Product.create(:name => 'Toshiba Laptop', :description =>
'Small, light quick laptop, robust chassis', :price =>
'1000.99')
Product.create(:name => 'Apple Macbook Pro', :description
=> 'Unibody alu Mac with 4GB memory', :price =>
'1500.00')
Product.create(:name => 'Lenovo Thinkpad', :description
=> 'Like an IBM laptop', :price => '899.99')
Product.create(:name => 'Dell', :description => 'Special
Offer', :price => '499.99')
Product.create(:name => 'Sony', :description => 'Huge
fancy screen laptop', :price => '2000.99')
14. The seeding mechanism in Rails uses the create method of our model (which
we get for free by using ActiveRecord, Rails ORM) to create an instance of a
product, assign the values we pass in as a hash to the appropriate fields and
then saves them to the database for us. All we have to do to run this file and
add the seed/sample data is:

C:\src\laptop_shop1> rake db:seed

15. Now when we refresh the home page of our application, we’ll see the product
listing page, with 5 newly seed products.

16. It would be useful for our customer to be able to search our products, so lets
add a way for our potential customers to do this.

17. Since the Products model/class will be responsible for doing anything that
relates to products, including searching for Products, that’s where we should
add the method to search. Go to the Product model file
(app/models/product.rb). And add the lines in bold below to your Product
model/class. These lines will add a class method which can be called without

class Product < ActiveRecord::Base

def self.search(search_query)
if search_query
find(:all,:conditions => ['name LIKE ?', "%#{
search_query}%"])
else
find(:all)
end
end
end
18. Next we need to wire the search method we have just created up to a
controller, to allow the user to access it via a controller action. So let’s open
the ProductsController (app/controllers/products_controller.rb).

19. We already have an action method in the ProductsController that gets


Products and displays them, that’s the index action. With only a few small
changes we can make this action show all products, or just the products that
satisfy the users search query.

Original version:
class ProductsController < ApplicationController
# GET /products
# GET /products.xml
def index
@products = Product.all

respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @products }
end
end

# ……………… Other code below


end

20. Replace line 5 of this file (“@products = Product.all”) with the code in
bold below (“@products = Product.search(params[:search])”)

New version:
class ProductsController < ApplicationController
# GET /products
# GET /products.xml
def index
@products = Product.search(params[:search_query])

respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @products }
end
end

# ……………… Other code below


end

21. Okay, so we have added a method to our model to search the database and
return any products that match our search query string. We have also added
search functionality to a controller action that is available to users. The last
thing we need to do to make search available is add a search field to a view
that will be displayed on a page for the user. (Once done we have made a
change to add this functionality at each layer of our MVC (Model-View-
Controller)).

22. The logical place to put the search is in the products#index view file, so lets
open that file from –
C:/src/laptop_shop1/app/views/products/index.html.erb

23. Add the following lines to the file we have just opened, after the closing table
tag (</table>) on line 25 is a good place:

<% form_tag products_path, :method => 'get' do %>


<p>
<%= text_field_tag :search_query,
params[:search_query] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>

Your file should now look something like this:

24. Now lets refresh the homepage of our app to see if it is displaying the form
we have added, including the text field for the search query and the search
button to submit the query to the controller action.

Our page should now look like this:


25. Try out the search functionality by putting in a query and clicking on search.
Make sure the correct search result(s) are returned and not all products. (I
searched for the string “ap” as this appears in the name of two of my
products).
26. And I get the expected results:

27. Next let’s expand our site and add a second Controller to add some higher
level actions to our site (Welcome/Home, Leaving/ThankYou, Register).

C:\src\laptop_shop1> rails generate controller welcome


home

28. Open the view file for the welcome#home action


(C:\src\laptop_shop1\app\views\welcome\home.html.erb) and add the
following view code:

<h1>Welcome to my Homepage</h1>
<p> Workshop1 </p>

29. Go to your browser and then go to http://127.0.0.1:3000/welcome/home to


check that the new action works as expected. You should see a page like
below:
30. Let’s make the welcome#home action be our default homepage/root. Go to
config/routes.rb and replace the line we updated earlier “root :to =>
"products#index" ” with:

root :to => "welcome", :action => "home"

NB: As before, we’ll need to restart the server in order for it to pick up this
change, so “Ctrl + c” to stop and then “rails server” to start again.

31. Let’s add a page for users leaving the site, by adding a thank_you action to our
WelcomeController. Open the welcome controller
(C:\src\laptop_shop1\app\controllers\welcome_controller.rb) and add a
method with the following definition:

def thank_you
end

Let’s also add a simple action to allow users to get to a basic register form
view:

def register
end

These methods don’t do anything on their own but it’s important to have
them to wire the views up and make the views available to the user to call
from their browser.

The WelcomeController should now look like this:

32. Just a couple more step to make these actions useable. We will create the
view files for each and then add routes for them, as they’re non-standard
actions (not the basic 7 CRUD ones). So go to
C:\src\laptop_shop1\app\views\welcome\ and create a file called
thank_you.html.erb …… then add the following contents:

<h1>Thanks for visiting!!</h1>

33. Next create another view file, this time called register.html.erb (in the same
location: C:\src\laptop_shop1\app\views\welcome\). Add the following
code to the file:

<h1>Register</h1>
<div class="field">
<%= label_tag :email %><br />
<%= text_field_tag :email %>
<br />
<%= label_tag :password %><br />
<%= password_field_tag :password %>
</div>

NB: This form won’t work yet ….. we’ll add to code to hook it up to a
create user action later.

34. Now go to the config/routes.rb file and add the following two routes for these
actions:

get "welcome/thank_you"
get "welcome/register"

35. Now let’s check those actions work by going to the following two pages:

http://127.0.0.1:3000/welcome/thank_you
http://127.0.0.1:3000/welcome/register

36. These 3 action that we have created in our welcome controller are the kind of
action that you normally want to have on every page. So let’s add links to
them to our default application layout file
(C:\src\laptop_shop1\app\views\layouts\application.html.erb).

(For more on Layouts …….


http://guides.rubyonrails.org/getting_started.html#customizing-the-layout)

37. In the default layout add the following lines of code before <%= yield %>:

| <%= link_to "Product Catalogue", products_path %> |


<%= link_to "Leave Site", :controller => "welcome",
:action => "thank_you" %> |
<%= link_to "Register", :controller => "welcome", :action
=> "register" %> |
<%= link_to "Home", :controller => "welcome", :action =>
"home" %> |
38. Now go back to the browser and go to the home page …… we should now
have a simple menu bar across the top of our site (we can worry about styling
it later):

39. Because we added the links to the layout, and the layout is used when
rendering every action (by default) ……. our links will now appear on every
page we go to, even the products page which we haven’t done anything to
change. Click on the “Product Catalogue” to see something like this:

40. That’s us finished with Tutorial 1. In the next installment we will add a User
Model and hook it up to our Register action. We will then be able to add some
login and authentication functionality to our app.

Das könnte Ihnen auch gefallen