Ruby on Rails 2.x hands-on

Source: Internet
Author: User
Tags ruby on rails
This article is original. Reprinted Please note:
Author: Utensil
Blog: http://blog.csdn.net/utensil/
Email: utensilcandel@gmail.com

In the past two days, the previous blog website based on XML and PHP has been transplanted to MySQL and ror to overcome two major difficulties in learning ror:

One is that most of the materials currently talk about the practices in rails 1.x, because 2.x interrupts a lot of backward compatibility (especially the dynamic scalffold)
How can we do the same in rails 2.x?

The second is how to use activerecord to access the database outside the rails framework.

This article briefly records my findings on these issues. Thanks to Google, but I am angry with the document form of rdoc and occasional serious omissions in some examples! We hope it will become more and more perfect.

Before running, the packages I installed through Yum include: (I am under fedora 8, Ruby is)

Ruby. i386
Ruby-RMagick.i386
Ruby-RMagick-doc.i386
Ruby-activerecord.noarch
Ruby-activesupport.noarch
Ruby-cairo.i386
Ruby-devel.i386
Ruby-docs.i386
Ruby-fam.i386
Ruby-gdkpixbuf2.i386
Ruby-glib2.i386
Ruby-irb.i386
Ruby-libs.i386
Ruby-mysql.i386
Ruby-rdoc.i386
Ruby-rsvg.i386
Ruby-shadow.i386
Ruby-sqlite3.i386
Rubygem-rake.noarch
Rubygems. noarch

The bold package is more important. Some packages cannot be directly used because dependency is automatically installed.

The packages installed in Ruby GEM are:

Actionmailer (2.1.1)
Actionpack (2.1.1)
Activerecord (2.1.1)
Activeresource (2.1.1)
Activesupport (2.1.1)
Htmlentities (4.0.0)
Rails (2.1.1)
Rake (0.8.3, 0.7.3)
Rubygems-Update (1.3.0)
Sources (0.0.1)
XML-simple (1.0.11)

The first question: (this is similar to radrails)

CD your workspace
Rails your project name

A lot of folders and files will be created. If you have a book about rails, he will introduce their structure to you. The paths used below are relative to the folder "your project name.

CD your project name

Now you can run

Ruby scripts/Server

To start the server inside Ruby. You can access the address reported by the browser (which looks like 0.0.0.0: port number) and you will see the welcome interface.

At this time, you should create a database. Take the MySQL database susanblog as an example. Suppose we have such a table in it:

Create Table 'blogs '(
'Id' int (10) unsigned not null auto_increment,
'Title' varchar (255) not null,
'Ctime' datetime default null,
'Content' text not null,
'Latestbak' text,
'Longetbak' text,
Primary Key ('id ')
) Engine = InnoDB auto_increment = 1 default charset = utf8

After the configuration is complete, modify config/database. yml. It is easy to understand. My yml Development Section is as follows:

Development:
Adapter: MySQL
Encoding: utf8
Database: susanblog
Username: Root
Password: root password, the one you set in MySQL
Socket:/var/lib/MySQL. Sock

Pay special attention to coding. incorrect coding may cause rails to strike. The encoding in yml must correspond to that in the database.

Yml is the cornerstone of scaffold.

Next we can establish saffold:

Ruby scripts/generate scaffold blog title: varchar ctime: datetime content: Text

The basic rule is Ruby scripts/generate scaffold model name field: datatype...

Field is your field name, And ype is the data type of SQL.

Note that the table name is blogs and the model name must be singular. If your table name is my_items, you can write my_item or myitem here.

ID does not need to be written. It is automatically added and does not need to be specified by the user. 'Latestbak' text and 'longetbak' text. They do not need to be empty, so they do not need to be written.

Now access localhost: Port Number/blogs will show all the entries in the database, and you can create, view, edit, and delete any entry. This is the legendary crud.

You can modify the ERB template in APP/views/blogs. x) to improve the interface, for example, in edit. the tinymce editor is added to ERB:

  1. <H1> edit log
  2. <% = Link_to 'show ', @ blog %> |
  3. <% = Link_to 'back', blogs_path %>
  4. <% Form_for (@ blog) Do | f | %>
  5. <% = F. error_messages %>
  6. <P>
  7. <% = F. Label: Title %> <br/>
  8. <% = F. text_field: Title %>
  9. </P>
  10. <P>
  11. <% = F. Label: ctime %> <br/>
  12. <% = F. datetime_select: ctime %>
  13. </P>
  14. <! -- Tinymce -->
  15. <% = Javascript_include_tag "tinymce/jscripts/tiny_mce" %>
  16. <SCRIPT type = "text/JavaScript">
  17. Tinymce. INIT ({
  18. // General options
  19. Mode: "textareas ",
  20. Theme: "advanced ",
  21. Skin: "o2k7 ",
  22. Plugins: "safari, style, table, save, advhr, advimage, advlink, emotions, conditions, insertdatetime, preview, searchreplace, contextmenu, paste, directionality, fullscreen, visualchars, nonbreaking, xhtmlxtras ",
  23. Editor_deselector: "mcenoeditor ",
  24. // Theme options
  25. Theme_advanced_buttons1: "Save, |, undo, redo, |, cut, copy, paste, pastetext, pasteword, |, search, replace, |, formatselect, fontselect, fontsizeselect, styleselect ",
  26. Theme_advanced_buttons2: "bold, italic, underline, strikethrough, |, HR, |, sub, sup, |, justifyleft, justifycenter, justifyright, justifyfull, |, bullist, numlist, |, outdent, indent, BLOCKQUOTE, |, forecolor, backcolor, styleprops, |, removeformat, cleanup ",
  27. Theme_advanced_buttons3: "link, unlink, image, charmap, emotions, |, insertdate, inserttime, |, tablecontrols, |, visualaid, visualchars, |, fullscreen, code, preview ",
  28. Theme_advanced_toolbar_location: "TOP ",
  29. Theme_advanced_toolbar_align: "Left ",
  30. Theme_advanced_statusbar_location: "bottom ",
  31. Theme_advanced_resizing: True,
  32. // Example content CSS (shocould be your site CSS)
  33. Content_css: "CSS/content.css ",
  34. });
  35. </SCRIPT>
  36. <! --/Tinymce -->
  37. <P>
  38. <% = F. Label: Content %> <br/>
  39. <% = F. text_area: content,: Id => 'elm1 '%>
  40. </P>
  41. <P>
  42. <% = F. Submit "Update" %>
  43. </P>
  44. <% End %>

Note <% = javascript_include_tag "tinymce/jscripts/tiny_mce" %>. This requires you to put the tinymce folder under public/javascripts. Rails has its own rules for path processing.

You can also sort indexes by using the index method in APP/models/blogs_controler.rb (yes, there is no list method ).
Set
@ Blogs = blog. Find (: All)
Change
@ Blogs = blog. Find (: All,: Order => "id DESC ")

Unfortunately, the paginate function has been deleted. It seems that a third-party library has been used for this purpose and it has not been used yet.

The second question is simply explained in an example. This is the script for converting the XML into MySQL.

  1. #! /Usr/bin/Ruby

  2. Require "rexml/document"

  3. Require "active_record"

  4. Activerecord: Base. establish_connection (
  5. : Adapter => "MySQL ",
  6. : Username => "user ",
  7. : Password => "password ",
  8. : Database => "susanblog ",
  9. : Host => "localhost ",
  10. : Encoding => "utf8"
  11. )

  12. Class blog <activerecord: Base
  13. End

  14. File = file. New "./susanblog_original.xml"
  15. Blogs = rexml: Document. New File

  16. # You can also use blogs. elements. Each ("blogs/blog") Do | E |, but I need to reverse the entire order.

  17. Ordered = blogs. get_elements ("blogs/blog"). Reverse!

  18. Ordered. Each do | E |
  19. Blog. New do | B |
  20. B. Title = E. get_text ("title"). to_s
  21. B. ctime = E. get_text ("timestamp "). to_s # Or we can use time. now. strftime "% Y-% m-% d % H: % m: % s"
  22. B. content = E. get_text ("content"). to_s
  23. B. Save
  24. End
  25. End

Writing this script is really hard, and the document is too imperfect. Note that the sentence B. Save is not mentioned in the document but must be saved after the value is changed. Later, it was discovered through hard exploration.

Using rexml is really a painful experience. We suggest you use xmlsimple. It is the best thing to use in PHP.

However, after I installed XML-simple, require was not enough. I had to put xmlsimple. Rb under/usr/lib/Ruby/gem and put it next to my script. (Next, try the legendary hpricot. It seems better.

I hope that the results of these explorations will help you avoid detours.

Major findings:

Previously, all the libraries installed with gems in require must be:

  1. Require 'rubygems'

In an instant, many things can be used. I have never said that, until the hpricot homepage, there is such a distinction (this step is not required for direct installation with Yum, but it is required for installation with Gem .)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.