Trying to peek into a WordPress database

I'm trying to use Rails to peek into some WordPress (weblog) database, using ActiveRecord. Retrieving posts works elegantly, even without one single line of code. Unfortunately, I can't retrieve associated data correctly, for example getting the categories of a post.

The relevant WordPress tables and fields are:

Table: wp_posts   id   ...

Table: wp_categories   cat_id   cat_name   ...

Table: wp_post2cat   rel_id   post_id   category_id

wp_post2cat is a join table, linking posts to categories.

In my Rails app, I've set up the following models:

File: app/models/post.rb   class Post < ActiveRecord::Base     has_and_belongs_to_many :categories, :join_table => "wp_post2cat"   end

File: app/models/category.rb   class Category < ActiveRecord::Base     set_primary_key "cat_id"     has_and_belongs_to_many :posts, :join_table => "wp_post2cat"   end

With this, a correct database.yml and the correct table prefix "wp_", I can correctly retrieve posts or categories:   p = Post.find(4812)   c = Category.find(10)

For now, trust me that post 4812 is associated to category 10. p.methods() shows that this object also has a method categories(), and c.methods() shows a posts() method.

The problem is that is isn't working:   p.categories() results in   

If I look to the resulting SQL-query, I see:   SELECT * FROM wp_categories   INNER JOIN wp_post2cat ON wp_categories.cat_id = wp_post2cat.category_id   WHERE (wp_post2cat.post_id = NULL )

I assume that the problem is in the WHERE-clause: post_id shouldn't be tested against NULL. If I replace NULL with 4812, I get the correct Category record.

Could someone locate the error in my setup, or provide pointers for further experimentation?

Many thanks, kind regards,

Jochem