Archive for the ‘Rails’ Category

It took a while to find this, but here’s my solution

Add this file: /Library/LaunchDaemons/org.postgres.launchd.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
        "http://www.apple.com/DTDs/PropertyList-1.0.dtd";>
<plist version="1.0">
<dict>
    
    <key>Label</key>
      <string>org.postgres.launchd</string>
    <key>Disabled</key>
      <false/>
    <key>UserName</key>
      <string>_pgsql</string>
    <key>GroupName</key>
      <string>_pgsql</string>
    <key>Program</key>
      <string>/usr/local/pgsql/bin/postmaster</string>
      <key>EnvironmentVariables</key>
      <dict>
              <key>PGDATA</key>
              <string>/usr/local/pgsql/data/</string>
      </dict>
    <key>RunAtLoad</key>
      <true/>
</dict>
</plist>

You can then load it and unload it by issuing:

$ sudo launchctl load /Library/LaunchDaemons/org.postgres.launchd.plist
$ sudo launchctl unload /Library/LaunchDaemons/org.postgres.launchd.plist

Now get to making some great Rails stuff!

Google search was un-obvious

psql databasename
\d table_name

[Rails] Associations

Monday, January 14th, 2008

Yesterday I found out I had made a major boo-boo in setting up an ActiveRecord::Association.

Imagine a “Widget” model that is composited of serveral other fields. You might think to yourself.

“An Widget has a SKU ( housed in table ‘skus’ based on model SKU ), a widget has a color, etc.”

You then might model your code such that

    Widget < ActiveRecord::Base
      has_one :sku
      has_one :color
    end

And accordingly

    SKU < ActiveRecord::Base
      belongs_to :widget
    end

This is wrong.

You must think in terms of the most “atomic” element. What’s the relationship of a SKU? A SKU “has one” product to which it is applicable. You see, what you’ve done above is absolutely reverse of the way it should be.

Think this way:

    SKU < ActiveRecord::Base
      has_one :widget
    end

And then just add the mirror entry, for completeness

    Widget < ActiveRecord::Base
      belongs_to :sku
    end

You can see this explained in the Rails API:

class Employee < ActiveRecord::Base
    has_one :o ffice
end

class Office < ActiveRecord::Base
   belongs_to :employee    # foreign key - employee_id
end

If you find yourself using the primary key of the composite entity to find something in the the constituent table or getting into weird sorts of problems with .create() or find yourself thinking that you may need to implement something like (although it is pretty cool):

    $ irb
    irb(main):001:0> class K
    irb(main):002:1> end
    => nil
    irb(main):003:0> k1 = K.new
    => #
    irb(main):004:0> k2 = eval('K').new
    => #
    irb(main):005:0> k3 = Object.const_get('K').new
    => #

[Reference]

The real difficulty here is with how English speakers construe the transitivity of the phrase “has one”. Does this mean:

  • X is a superior containing entity i.e. “contains” (“The happy meal has one hamburger and one toy”)
  • X is uniquely assigned in a relationship (“The parolee has one parole officer”)

The word “relationship” in the second bullet is the use of “has_one” that Rails uses the phrase “has_one” to signify.

If, when getting your object model to work in Rails seems really hard and sorta backwards, you should say “this seems needlessly hard, maybe I’m doing it the wrong way” and bail out of that design. The LOLCatz rules apply here: “Using Rails to make your life easy - ur doin’ it wrong

Me lately…

Friday, January 11th, 2008

Rails…
…Lauren
Rails…
…work
Rails…
…school next week
Rails…
…Unicode
Rails…
…fingers hurt

[Rails] Cleaning up HABTM views (2/2)

Friday, January 11th, 2008

You may want to see the previous entry on this topic. We’ll be using that application.

The reality is that most people use Rails for web frameworks … the console manipulation stuff we explored in the previous post doesn’t really help us much. We need a web interface. While using the script/generate gave us some scaffolds that we can play with ( http://localhost:3000/candies or ../flavors ), it’s not really “integrated” and it doesn’t quite demonstrate the “has many”-ness.

First we’ll fire up the web server (script/server) and see what the ‘new’ view looks like:

ss2.

Hm, that’s certainly not giving us any place to enter some flavorful information. Let’s fix that in the view.

(more…)

The concept: “Many to Many” relationships

Many things in this life have a one to one relationship: a man has a wife ( Utah excepted ), a car has an owner, a dog it’s day. Many other things in life have a one to many relationship: a policy covers many people, a manager has direct reports, etc. But some things have a many to many relationship. People have surnames (“John Smith” is a Smith and so is “Jane Smith”;conversely, among the Smith clan there might be multiple Johns, 42 Janes, and 22 Larry’s ).

It is of this many to many relationship I will write and whose code I seek to share.

In this world there are many candies ( “Now and Laters”, “Sweet Tarts”, and “Kasugai’s Gummies” ) and candies have a flavor (chocolate, strawberry, cherry, and for my readers of an Oriental persuasion, lychee).

There are many candies which have a flavor, and a particular flavor has many candies which apply to it. This is a perfect, and simple example wherewith to demonstrate Rails’ ActiveRecord’s Associations.

(more…)

  1. Examine the Unicode standard’s code page collection for “Latin small letter a with macron”.

  2. Nets U0100.pdf

  3. “Latin small letter a with macron” appears on chart as 0101. This is a hexidemial number which points to U+0101 as its code point. Converting 0101 to decimal gets you 257, this is the same as the HTML entity code. Thus one can enter either &#257; or &amp#x0101; and get the right glyph [ā|ā]

  4. Put ā character into a view via Rails that is back-ended by a PostGres database.

  5. Using script/console, write the collection of models that contain this accented character to a YAML file.

  6. “Latin small letter a with macron” is stored in a YAML dump of accented charcters as: \xC4\x81

  7. Hm, OK that’s a start. Somehow 0101 or 257 is linked to C4 81. How? I know, BTW, the database that holds that entry is in UTF-8 as psql -l shows this.

  8. C4: 196

  9. 81: 129

  10. 196+129=325 != 0101. Hm, look at documentation.

  11. Be stumped.

  12. Send mail to mailing lists for help.


In the immortal words of Sid Meier’s “Civilization”: “Time Passes…”


  1. \xC4\x81 is the UTF-8 encoding for the Unicode code point U+0101.

  2. [Q:] Which table does U+0101 fall into?

    [A:] “So the first 128 characters (US-ASCII) need one byte. The next 1920 characters need two bytes to encode. This includes Latin alphabet characters with diacritics, Greek, Cyrillic, Coptic, Armenian, Hebrew, and Arabic characters. The rest of the BMP characters use three bytes, and additional characters are encoded in four bytes.”

  3. OK this means that the code point will be of the form: “110yyyyy 10zzzzzz

  4. We will now work to fill in the “y” and “z” values:

  5. Hexidecimal “U+0101” converts to binary: “100000001

  6. There are 5 y’s and 6 z’s. So let’s split the above number to match that form: “[00]100-000001”. Note, we moved from the right. Where the leading 0’s were required to turn 100 into 00100, they were pre-pended.

  7. Integrate and produce: “110” + “00100” : “10” + “000001” => 11000100 : 10000001

  8. Take THESE numbers and convert them back to hex => c4 81

  9. String notation for this is \xc4\x81 - violá!

  10. Figuring this out letter by letter is a major pain in the keester. A good URL resource is: Fileformat.info or, handily a URI of the form:

http://www.fileformat.info/info/unicode/char/<unicode char value>/index.htm

Special Thanks to: Michael Flester

This is more of a reminder to me for when I bang my head against the wall often and hard

>>reload!

Changes introduced by rake db:migrate and other tools will not be integrated into the console environment until you reload!

Rails: Loading test data with fixtures

Saturday, January 5th, 2008

Rails canonical story is:

  • “Fixtures are used to load sample data before a unit test”.
  • “Migrations are used to build DB tables and alter structure of contents thereof ( e.g., delete the “name” column and split the field on comma and put the resultant entries into the “firstname” column and the “lastname” column )”

But what if you need to bring in some good data — not test data, but data that you want for testing and seeing how things look with a “real” data set? What then smarties?

Here was my situation: I had entered data via the scaffolded interface and the the data included many unicode characters (&258;éæ, etc.). I wrote a little JavaScript table specifically to make entering these characters easy from an English keyboard.

I knew that I was going to invariably mess up the data and wanted to have the ability to get this preliminary data set back in ( it’s just safer that way ).

Furthermore the datas contained Unicode and I’ve just not had time to wrap my head around “entering Unicode values via command line into PostGres.

I dumped the data to a YML file with:

[code lang="ruby"]
x=File.open("models.yml")  
x.puts Model.find(:all).to\_yaml  
x.close  
[/code]

Looking at that Yaml data, I have my records.

I put that information into ../test/fixtures/models.yml

This file requires a bit of editing.

You will start with entries that look like:

    - !ruby/object:Model 
      attributes: 
        updated_at: 2008-01-04 19:32:10.874607
        id: "5"
        classification: Fourth
        created_at: 2008-01-04 19:32:10.874607
      attributes_cache: {}

You want to turn this into….

first:
  updated_at: 2008-01-04 19:32:10.874607
  id: "5"
  classification: Fourth

That is, reduce the indents of the “meaty data”, remove the “- !ruby” declaration and then put a numbering tag ( “first” ). This will help you import. You may find it handy to try the following in the console:

[code lang="ruby"]
directory="./test/fixtures"
require 'active_record/fixtures'
Fixtures::create_fixtures( directory, "models")
Conjugation.find(:all)
[/code]

Obviously, good data here is a good sign; errors, a sign of more work.

Then with rake db:load:fixtures I could get my data back in….but I wanted to make this addition hinge on a migration, so that I could move forward and backwards in the migration queue. Thanks to the skateboard book p.273 I found a way.

First I created a migration script/generate migration importBaselineData

Edit the 0xx_import_baseline_data.rb

[code lang="ruby"]
require 'active_record/fixtures'  
  
class LoadSampleData < ActiveRecord::Migration  
  def self.up  
    directory = File.join(File.dirname(__FILE__), "../../test/fixtures")  
    Fixtures::create_fixtures( directory, "models")  
  end  
  
  def self.down  
    Model.delete_all  
  end  
end  
[/code]

Thus with a rake db:migrate my migration with data entry gets entered.

This is the mail that I sent to Rails-list which describes my issues around the Rails scaffolding in Rails 2.0. Extensive debugging information can be found in my diagnostic research post.


Hello,

I’ve read the (many) re-posts about problems around scaffolding in Rails 2.0 and have followed a number of tutorials and fully understand “how to scaffold” from a technical perspective, but I don’t understand the mindset of how to use the new scaffolding. It seems like a productivity- / agility- regress and I’m thinking I may have failed to properly grok the new setup. In the interest of full disclosure, I’m coming back to Rails after being in other toolkits for about 9 months.

Thanks to the intrepid work of Sean Lynch at ( http://fairleads.blogspot.com/2007/12/rails-20-and-scaffolding-step-by-step.html ) I found a tutorial that would familiarize me with the raw “how to scaffold” material.

I followed his tutorial’s step of:

“ruby script/generate scaffold Movie”

Great! From that point I filled in the “columns” in the migration as I had done in Rails 1.x. All I should need to do is run “rake db:migrate” and try adding a new record via the dynamically-created view.

When I started the server and navigated localhost:3000/movies I had the “create new” button. When I pushed that button there were no text widgets to enter despite having defined the columns that corresponded to said widgets having been added to the migration ( I have a lengthy blog post about how my diagnostics went, for anyone else’s edification ). In short the scaffold that had been created knew nothing of the columns I had added in the migration and, as such, the ‘new’ view had no widgets.

This struck me as well, wrong. On Sean’s post another user confirms the same experience. I have tried it with sqlite3 / mysql / postgres connectors.

Research showed that the scaffold had remained static relative to the time that I had done the original aenemic invocation. Per “script/generate scaffold —help”:

./script/generate scaffold post` # no attributes, view will be anemic

To fix this I had to re-issue the script/generate command with all the attributes in “final draft” mode ( “script/generate scaffold movie title:string text:description one_sheet_url:string” ) and then over-write the old templates ( output stored below, for legibility, Fig. 1).

The solution implies:

  • You have to get the script/generate command’s “attributes” arguments perfect at time of creation OR
  • You do this overwriting thing that I describe below.

As I recall Rails 1.x’s dynamic scaffolding allowed us to use a scaffold flexibly strictly based on migrations and rake db:migrate. This flexibility allowed us to “sketch” ideas very rapidly. Or is it considered a “Good Thing” that you get a “perfected” “generate scaffold” command at some point? If so, what’s the reasoning? Am I missing some sort of rake command that “refreshes” the scaffold templates?

Based on the comments at Sean’s site and some of the questions in the comments to DHH’s Rails 2. announcement I think there are others grappling with this quandry as well. Can anyone help?

Steven

(more…)