Forum: Ruby on Rails Trying to peek into a WordPress database

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
25b78ea128b61107fc07250603c981e2?d=identicon&s=25 Jochem Schulenklopper (Guest)
on 2007-01-09 03:59
(Received via mailing list)
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

Table: wp_categories

Table: wp_post2cat

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"

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

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:
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 =
  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,

This topic is locked and can not be replied to.