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:
- <H1> edit log
- <% = Link_to 'show ', @ blog %> |
- <% = Link_to 'back', blogs_path %>
- <% Form_for (@ blog) Do | f | %>
- <% = F. error_messages %>
- <P>
- <% = F. Label: Title %> <br/>
- <% = F. text_field: Title %>
- </P>
- <P>
- <% = F. Label: ctime %> <br/>
- <% = F. datetime_select: ctime %>
- </P>
- <! -- Tinymce -->
- <% = Javascript_include_tag "tinymce/jscripts/tiny_mce" %>
- <SCRIPT type = "text/JavaScript">
- Tinymce. INIT ({
- // General options
- Mode: "textareas ",
- Theme: "advanced ",
- Skin: "o2k7 ",
- Plugins: "safari, style, table, save, advhr, advimage, advlink, emotions, conditions, insertdatetime, preview, searchreplace, contextmenu, paste, directionality, fullscreen, visualchars, nonbreaking, xhtmlxtras ",
- Editor_deselector: "mcenoeditor ",
- // Theme options
- Theme_advanced_buttons1: "Save, |, undo, redo, |, cut, copy, paste, pastetext, pasteword, |, search, replace, |, formatselect, fontselect, fontsizeselect, styleselect ",
- Theme_advanced_buttons2: "bold, italic, underline, strikethrough, |, HR, |, sub, sup, |, justifyleft, justifycenter, justifyright, justifyfull, |, bullist, numlist, |, outdent, indent, BLOCKQUOTE, |, forecolor, backcolor, styleprops, |, removeformat, cleanup ",
- Theme_advanced_buttons3: "link, unlink, image, charmap, emotions, |, insertdate, inserttime, |, tablecontrols, |, visualaid, visualchars, |, fullscreen, code, preview ",
- Theme_advanced_toolbar_location: "TOP ",
- Theme_advanced_toolbar_align: "Left ",
- Theme_advanced_statusbar_location: "bottom ",
- Theme_advanced_resizing: True,
- // Example content CSS (shocould be your site CSS)
- Content_css: "CSS/content.css ",
- });
- </SCRIPT>
- <! --/Tinymce -->
- <P>
- <% = F. Label: Content %> <br/>
- <% = F. text_area: content,: Id => 'elm1 '%>
- </P>
- <P>
- <% = F. Submit "Update" %>
- </P>
- <% 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.
- #! /Usr/bin/Ruby
- Require "rexml/document"
- Require "active_record"
- Activerecord: Base. establish_connection (
- : Adapter => "MySQL ",
- : Username => "user ",
- : Password => "password ",
- : Database => "susanblog ",
- : Host => "localhost ",
- : Encoding => "utf8"
- )
- Class blog <activerecord: Base
- End
- File = file. New "./susanblog_original.xml"
- Blogs = rexml: Document. New File
- # You can also use blogs. elements. Each ("blogs/blog") Do | E |, but I need to reverse the entire order.
- Ordered = blogs. get_elements ("blogs/blog"). Reverse!
- Ordered. Each do | E |
- Blog. New do | B |
- B. Title = E. get_text ("title"). to_s
- B. ctime = E. get_text ("timestamp "). to_s # Or we can use time. now. strftime "% Y-% m-% d % H: % m: % s"
- B. content = E. get_text ("content"). to_s
- B. Save
- End
- 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:
- 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 .)