11.13.07

ActiveRecord has_one versus belongs_to (finally understood)

Posted in Programming, Ruby at 6:57 pm by Robert Horvick

I spent some time googling for an answer to the question I’ve had about when to use has_one or belongs_to.  I came across Duane’s blog where he addressed this exact issue.

Ultimately the phrase that made it sink in was:

“With belongs_to, the table accepts responsibility for the foreign key. With has_one, the table expect the other table to hold it.” (which he attributes to this wiki).

The main shift is that I need to stop thinking in terms of the foreign keys and not the containing objects.

So thanks, Duane.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

ActiveRecord tasklist exercise: adding task state

Posted in Uncategorized at 12:45 am by Robert Horvick

Last time I used ActiveRecord to persist basic tasks.  On the list of features to implement was task state such as “New” or “Complete”.

I wanted to make sure that tasks were used definable and that the relationship at the class level did more than just expose an int that the user had to map to the proper state.

I started by defining the new SQL schema for tasks with states.  The schema I created follows:

CREATE TABLE tasks (
  `id` INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
  `title` VARCHAR(255) DEFAULT NULL,
  `state_id` INT DEFAULT NULL

);CREATE TABLE states (
  `id` INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(255) NOT NULL
);

I did not realize that the name of the state_id column needed to be “state_id”.  This makes sense and reveals a bit about how ActiveRecord works without the attribution requirements that other ORM systems have.

Next I added a new class for the State and added a relationship to Task.  My thinking was “Each Task has one state.  So use has_one.”  It looked like:

class Task < ActiveRecord::Base
  has_one :state
end

class State < ActiveRecord::Base
end

Marginally more experienced people probably already see the problem.  The error I got when trying to run was:

Exception: Mysql::Error: Unknown column 'states.task_id' in 'where clause': SELECT * FROM states WHERE (states.task_id = 17)  LIMIT 1

Ok - that’s backwards from what I expected.  I assumed that since the Task “has_one” State that the ID being looked for would be the state ID, not the task ID. I did some digging and found that belongs_to and has_one are commonly confused cousins.  And I found this blog post about it.  So I need to change has_one to belongs_to and I need a has_many relationship defined as well. 

Now the code looks like:

class Task < ActiveRecord::Base
  belongs_to :state
end

class State < ActiveRecord::Base
  has_many :task
end

That worked as expected (I should say “as hoped” since my expectation was that has_one would work).  I have to admit I need more time to wrap my noggin around has_one vs. belongs_to.

Now with this in place I was able to write the following code:

state_new = State.create "name" => "New"
state_ip = State.create "name" => "In Progress"

state_complete = State.create "name" => "Complete"Task.create "title" => "Attend Raleigh Ruby Brigade November Meetup", "state" => state_new
Task.create "title" => "Attend mid-day scrum", "state" => state_complete
Task.create "title" => "Add state support to task list", "state" => state_ip

Task.find(:all).each { |t| puts "#{t.title} (#{t.state.name})" }

Which had the following output:

Attend Raleigh Ruby Brigade November Meetup (New)
Attend mid-day scrum (Complete)
Add state support to task list (In Progress)

Which was exactly what I expected.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Quieting MySQL - Disabling beep in Windows.

Posted in MySQL, Programming at 12:17 am by Robert Horvick

I write code in bed at night on my laptop.  I tend to make typos in the dark (yeah … that’s why).  In MySQL interactive shell an error generates a beep on windows (ASCII BEL).  It is loud.  Being night, this bothers my wife.  I need to avoid this.

I googled for “disable beep in mysql” and the first hit was MySQL bug 17088 “Command line tools beep too loud on Windows”.

The answer?  Turn off the beep service on windows.

> net stop beep

Beeps stopped.

Wife sleeps.

Typos continue.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

11.12.07

Getting friendly with ActiveRecord (without Rails)

Posted in Programming, Ruby at 8:06 pm by Robert Horvick

I’ve been puttering around Ruby and Rails for a while now but it’s been mostly surface-level stuff.  Following examples, customizing little things here and there.  But I haven’t really dived in and gotten my hair wet.

Since I’m off the merb wagon the next task on the list was getting more familiar with ActiveRecord without getting bogged down in Rails and all things Webish.

My starting point was the excellent tutorial that I’m, in some ways, going to restate in this blog.

I started by connecting to MySQL and creating a database (TaskList) and a task table:

CREATE TABLE tasks (
  `id` INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
  `title` VARCHAR(255) DEFAULT NULL
);

I deviated from the tutorial slightly here by adding AUTO_INCREMENT to the id column.  This makes creating the objects a little easier because I can let SQL worry about their ID assignments.

Next I took the sample code from the tutorial, customized it for my settings, and added a little flare at the end:

require 'rubygems'

require 'active_record'ActiveRecord::Base.establish_connection({
      :adapter => “mysql”,
      :username => “root”,
      :database => “TaskList”
})

# define a simple model

class Task < ActiveRecord::Base
end

eat     = Task.create “title” => “Eat”
drink   = Task.create “title” => “Drink”
bemerry = Task.create “title” => “Be Merry”

Task.find(:all).each { |t| puts t.title }

The program output is:

Eat

Drink

Be Merry 

Running it subsequent times adds new tasks with the same values:

Eat
Drink
Be Merry
Eat
Drink
Be Merry

So nothing ground breaking here.  I read a tutorial.  I did what it said.  It worked.  Life is good.

Now it’s time to start branching out a little.  Things I want to do now are:

  • Add support for task states (start with static and add support for user defined)
  • Have the ability to assign tasks to users
  • Add a due date to tasks

This should give me the basics for some simple relations.  With that foundation I should have enough footing with ActiveRecord that I’m ready to move on to something else.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

11.11.07

Ruby on Windows Blog

Posted in Programming, Ruby at 7:09 pm by Robert Horvick

I was going through RubyCorner’s updated blog list and the top of the list is the Ruby on Windows blog.  Looks like a decent source of information.  If you, like myself, are primarily interested in Ruby development on Windows then check it out.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Merb on Windows: Need to have gcc installed. Forget it … I’m done.

Posted in Programming, Ruby, merb at 2:12 pm by Robert Horvick

[Update: Merb is now working on Windows

Previously I ran into this error when trying to get merb running on Windows:

C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/RubyInline-3.6.5/lib/inline.rb:397:in ``': No such file or directory - cl -nologo -LD -Werror  -MD -Zi -O2b2xg- -G6 -I C:/InstantRails/ruby/lib/ruby/1.8/i386-mswin32 -I C:/InstantRails/ruby/include -o "C:/Users/Robert/AppData/Local/Temp/.ruby_inline/Inline_ParseTree_fa12.so" "C:/Users/Robert/AppData/Local/Temp/.ruby_inline/Inline_ParseTree_fa12.c"  -link /LIBPATH:"C:/InstantRails/ruby/lib" /DEFAULTLIB:"msvcrt-ruby18.lib" /INCREMENTAL:no /EXPORT:Init_Inline_ParseTree_fa12 (Errno::ENOENT)
 from C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/RubyInline-3.6.5/lib/inline.rb:397:in `build'
 from C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/RubyInline-3.6.5/lib/inline.rb:679:in `inline'
 from C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/ParseTree-2.0.2/lib/parse_tree.rb:243
 from C:/InstantRails/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require'
 from C:/InstantRails/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require'
 from C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/ruby2ruby-1.1.7/lib/ruby2ruby.rb:4
 from C:/InstantRails/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:32:in `gem_original_require'
 from C:/InstantRails/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:32:in `require'
  ... 13 levels...
 from C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/merb-0.4.1/lib/merb/server.rb:500:in `run'
 from C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/merb-0.4.1/bin/merb:6
 from C:/InstantRails/ruby/bin/merb:16:in `load'
 from C:/InstantRails/ruby/bin/merb:16

It turns out that merb depends on RubyInline which is the Ruby way to generate C code via Ruby.  Why does it require C code generation?  Honestly I’m not interested enough to continue digging.  I’m not installing gcc on this box.  A quick glance into inline.rb shows that this is a gcc-specific generator and I’m not inclined to spend a day writing the VC interface just to get another step further with merb.

Perhaps I’ll try merb out on my desktop sometime - I dual boot it to Ubuntu - but the point of having it on the laptop was so that I could veg out in bed after the kids were asleep and the wife and I are winding down (and I’m not putting Ubuntu on this machine - Vista is very stable and everything is working how I want it - I’m not going to tempt fate by changing partitions and adding grub).  I know I could remote in to the desktop via any number of protocols but this was just to see what I thought of merb.  I think at this point I’ve figure that out.

Merb looks interesting but has taken, so far, a very unix-centric development turn.  Rails is far more platform neutral and is therefore more compelling to me.

I’ll continue to keep an eye on merb, though.  It looks promising.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Merb on Windows: environment variables required.

Posted in Programming, Ruby, merb at 1:56 pm by Robert Horvick

[Update: Merb is now working on Windows]  

After getting merb installed I created a project using “merb myapp” - this worked fine.  Next I tried just running “merb” to see where I was at.

Merb started with these options:---:merb_root: C:/InstantRails/projects/merb_1/myapp 

:reloader_time: 0.5
:cache_templates: false
:use_mutex: true
:session_id_cookie_only: true
:session_secret_key: C:/INSTANTRAILS/PROJECTS/MERB_1/MYAPP5259
:host: 0.0.0.0 

:query_string_whitelist: []
:reloader: true
:exception_details: true
:environment: development
:port: “4000″
Define INLINEDIR or HOME in your environment and try again

The error “Define INLINEDIR or HOME in your environment and try again” was not expected but I’m game.

I looked around for a place to define environment variables (since “:environment: development” seemed to hint that there would be one).

So I tried the obvious directory listing:

C:\InstantRails\projects\merb_1\myapp>dir development.rb /s 

 Volume in drive C has no label. 

 Volume Serial Number is 2256-DBBA 

Directory of C:\InstantRails\projects\merb_1\myapp\config\environments 

11/11/2007  12:48 AM                44 development.rb 

               1 File(s)             44 bytes 

I opened it and changed it’s contents to:

puts "Loaded DEVELOPMENT Environment..." 

ENV['INLINEDIR'] = “C:/Users/Robert/AppData/Local/Temp”

But the error persisted.  So I just set INLINEDIR in the environment.

Further … but now a new error:

C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/RubyInline-3.6.5/lib/inline.rb:397:in ``': No such file or directory - cl -nologo -LD -Werror  -MD -Zi -O2b2xg- -G6 -I C:/InstantRails/ruby/lib/ruby/1.8/i386-mswin32 -I C:/InstantRails/ruby/include -o "C:/Users/Robert/AppData/Local/Temp/.ruby_inline/Inline_ParseTree_fa12.so" "C:/Users/Robert/AppData/Local/Temp/.ruby_inline/Inline_ParseTree_fa12.c"  -link /LIBPATH:"C:/InstantRails/ruby/lib" /DEFAULTLIB:"msvcrt-ruby18.lib" /INCREMENTAL:no /EXPORT:Init_Inline_ParseTree_fa12 (Errno::ENOENT) 

 from C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/RubyInline-3.6.5/lib/inline.rb:397:in `build' 

 from C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/RubyInline-3.6.5/lib/inline.rb:679:in `inline' 

 from C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/ParseTree-2.0.2/lib/parse_tree.rb:243 

 from C:/InstantRails/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require' 

 from C:/InstantRails/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require' 

 from C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/ruby2ruby-1.1.7/lib/ruby2ruby.rb:4 

 from C:/InstantRails/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:32:in `gem_original_require' 

 from C:/InstantRails/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:32:in `require' 

  ... 13 levels... 

 from C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/merb-0.4.1/lib/merb/server.rb:500:in `run' 

 from C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/merb-0.4.1/bin/merb:6 

 from C:/InstantRails/ruby/bin/merb:16:in `load' 

 from C:/InstantRails/ruby/bin/merb:16

Is it just me or does that look like it’s trying to run a C compiler?

Investigating now…

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Installing Merb on Windows required Rakefile tweaks for sudo and chmod

Posted in Programming, Ruby, merb at 12:32 am by Robert Horvick

[Update: Merb is now working on Windows and the errors described in this post have been fixed in the latest svn trunk]  

Following the merb installation stepson my Vista laptop I discovered that the “rake install” was failing because the Rakefile contained explicit calls to sudo (and chmod).

When executing “rake install” the result was:

 C:\InstantRails\merb>rake install
(in C:/InstantRails/merb)
rake package
(in C:/InstantRails/merb)
  Successfully built RubyGem
  Name: merb
  Version: 0.4.1
  File: merb-0.4.1.gem
sudo gem install pkg/merb-0.4.1 --no-rdoc --no-ri
rake aborted!
Command failed with status (0): [sudo gem install pkg/merb-0.4.1 --no-rdoc ...]
C:/InstantRails/merb/rakefile:76
(See full trace by running task with –trace) 

 I modified the Rakefile to not use sudo on win32 (replacing it with “” instead) and to only execute chmod when not win32.  The patch is:

Index: Rakefile
===================================================================
--- Rakefile (revision 937)
+++ Rakefile (working copy)
@@ -16,6 +16,8 @@
 NAME = "merb"
 VERS = "0.4.1"
 CLEAN.include ['**/.*.sw?', '*.gem', '.config']
+
+SUDO = (PLATFORM =~ /win32/)? “” : “sudo”
 
 setup_clean [ "pkg", "lib/*.bundle", "*.gem", "doc/rdoc", ".config", 'coverage', "cache"]
 
@@ -73,11 +75,11 @@
 
 task :install do
   sh %{rake package}
-  sh %{sudo gem install pkg/#{NAME}-#{VERS} –no-rdoc –no-ri}
+  sh %{#{SUDO} gem install pkg/#{NAME}-#{VERS} –no-rdoc –no-ri}
 end
 
 task :uninstall => [:clean] do
-  sh %{sudo gem uninstall #{NAME}}
+  sh %{#{SUDO} gem uninstall #{NAME}}
 end
 
 desc “run webgen”
@@ -89,7 +91,7 @@
 task :doc_rforge do
   sh %{rake doc}
   sh %{rake doc_webgen}
-  sh %{sudo chmod -R 755 doc}
+  sh %{#{SUDO} chmod -R 755 doc} if not PLATFORM =~ /win32/
   sh %{scp -r -p doc/site/output/* ezmobius@rubyforge.org:/var/www/gforge-projects/merb}
   sh %{scp -r -p doc/rdoc/* ezmobius@rubyforge.org:/var/www/gforge-projects/merb/rdoc}
 end

I haven’t really thought about what the consequences of this change are but I did file a bug at the merb Trac in the event they want to fix platform blockers at this point in the dev cycle.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

11.09.07

Free Ruby Book (PDF) - 21 days left!

Posted in Programming, Ruby at 11:14 pm by Robert Horvick

I was reading Cavlyn blog and they mentioned that SitePoint is offering “Build Your Own Ruby on Rails Web Application” for free in PDF form.  Since I already own this in hardcopy I was pleased to be able to get a PDF copy for the laptop so I can stop lugging the hardcopy around (I still need to refer back to it periodically - I’m still not fluent in the Rails development workflows).

It’s a good book at a great price.  Only 21 days left though so get moving.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Ruby is more of a weekend language

Posted in Programming, Ruby at 9:16 pm by Robert Horvick

Over the year I’ve had a growing interest in the Ruby programming language.  I’ve been attending the local Ruby Meetups, reading The Ruby Way and creating Rails based sites.  I’m still swimming in the shallow end but it’s all clicking. 

But at the end of the day Ruby is my weekend language.  It’s how I unwind, not how I pay the bills.

Apparently I’m not the only one.  Google Trends shows that the search term “Ruby” remains steady, and even ticks upwards, over the weekend.  Comparable terms, “Perl” and “Python”, exhibit a sharp decline on our days of rest.

 Ruby search term trends upwards on weekends.

Is a picture really worth 1000 words?

I won’t draw any hard conslusions from this - there are too many ways to interpret the graph. 

Does this mean that there are more professional Perl and Python developers so when they cut out for the weekend the traffic declines?  Perhaps they are all just closest Rubyists who go home and spend their free time writing Rails apps.  Perhaps Ruby developers work seven days a week.

Or maybe I’m not the only one who enjoys the Ruby experience.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Next entries »