Это, кажется, работает для меня (я загружаю из Wordpress в качестве вторичной базы данных, поэтому establish_connection()
вызывает и переопределяет table_name
.
class Term < ActiveRecord::Base
establish_connection "wordpress-#{Rails.env}"
self.table_name = "wp_terms"
has_one :term_taxonomy
end
class TermTaxonomy < ActiveRecord::Base
establish_connection "wordpress-#{Rails.env}"
self.table_name = "wp_term_taxonomy"
belongs_to :term
has_many :term_relationship
end
class TermRelationship < ActiveRecord::Base
establish_connection "wordpress-#{Rails.env}"
self.table_name = "wp_term_relationships"
belongs_to :post, :foreign_key => "object_id"
belongs_to :term_taxonomy
has_one :term, :through => :term_taxonomy
end
class Post < ActiveRecord::Base
establish_connection "wordpress-#{Rails.env}"
self.table_name = "wp_posts"
has_many :term, :through => :term_relationship
has_many :term_relationship, :foreign_key => "object_id"
has_one :postmeta
# we only care about published posts for notifications
default_scope where("post_type = 'post' and post_status = 'publish'")
end
class Postmeta < ActiveRecord::Base
establish_connection "wordpress-#{Rails.env}"
self.table_name = "wp_postmeta"
belongs_to :post
end
Затем я оборачиваю категорию впростой рубиновый объект, облегчающий доступ к данным:
class WPCategory
attr_accessor :id
attr_accessor :name
attr_accessor :description
attr_accessor :term
def self.categories()
categories = Term.all()
categories = categories.select{|term| term.term_taxonomy.taxonomy == "category"}
return categories.map{|term| WPCategory.new(term)}
end
def self.category(id=nil)
if id
term = Term.find(id)
if term.term_taxonomy.taxonomy == "category"
return WPCategory.new(term)
end
end
return nil
end
def initialize(term)
@id = term.term_id
@name = term.name
@description = term.term_taxonomy.description
@term = term
end
def to_s
return "Wordpress Category: '#{@name}' (id=#{@id})"
end
end