I've written a Ruby script that parses a tab-delimited text file and writes the output to a sqlite3 database with ActiveRecord. Next, I need to write another Ruby script to display the database's contents as static HTML.
The text file that I'm working with is a list of parts that my company has for sale. My database has one table; each row in the database is a different part, and each column is a different attribute of that part (i.e., size, weight, list price, and so on and so forth). I need to be able to sort the table by the "short description" column in alphabetical order, then output each row as a series of HTML tables.
I've got no idea what to do next. I've been working with Ruby for about two weeks, and I've been using ActiveRecord for about four days, so I'm a little lost. I've been Googling for an answer all morning, but I've not found anything like what I'm wanting to do.
Here's a copy of the sqlite3 table declaration, if it's any help:
CREATE TABLE parts_info(item_number INTEGER PRIMARY KEY ASC, location TEXT,
quantity INTEGER, make TEXT, year INTEGER, model TEXT, serial TEXT, volt INTEGER,
phase INTEGER, weight INTEGER, list_price REAL, sold INTEGER,
image_path TEXT, short_desc TEXT, lo开发者_Python百科ng_desc TEXT, junk TEXT);
It very well may be that I'm approaching this from the wrong angle, and if that's the case, I am open to any suggestions as to how to do this better.
The idea with activerecord is that you have a model that represents a row in your table, and activerecord automatically maps data from the database into instances of your object, and vice versa.
So, to create an HTML table, you want to retrieve a list of PartsInfo objects, and convert them to HTML. There are a number of options to do that: You may want to use an ERB template file to turn your object into the desired HTML. You might want to look at the Builder gem.
Edited to add: To get a list of the objects, you use the ActiveRecord query methods. E.g. PartsInfo.all
.
If you're using an ActiveRecord model, you can return the entire contents of the model's table with ModelName.all
. Another option for iterating over all records in a table is the ModelName.find_each
method. This lets you effeciently do something like the following.
ModelName.find_each do |model_var|
<tr>
<td>model_var.attribute_1</td>
<td>model_var.attribute_2</td>
# and so on...
</tr>
end
Obviously this is very simple, perhaps even primitive, but if all you need is dump text to a file, this will work. If you need to construct this html on the fly, then you should look into an MVC framework like Rails or Sinatra.
精彩评论