这似乎对我有用(我从Wordpress加载作为辅助数据库,因此调用和覆盖.这应该大部分方式在那里,让你访问Wordpress数据作为ActiveRecord对象。我还没有编写帖子()的包装器,以使它们从API的角度来看更加用户友好,但这应该适用于基于Rails的Wordpress数据显示。establish_connection()
table_name
WPPost
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
然后,我将类别包装在一个简单的 ruby 对象中,这样可以轻松访问数据:
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
这是我的 database.yml(确保您的数据库用户对 wordpress 数据库具有只读访问权限,以避免任何 ActiveRecord 事故):
test:
adapter: mysql2
encoding: utf8
database: test-rails
pool: 5
username: test
password: XXXXXX
socket: /var/lib/mysql/mysql.sock
wordpress-test:
adapter: mysql2
encoding: utf8
database: test-wordpress
pool: 5
username: test
password: XXXXXXX
socket: /var/lib/mysql/mysql.sock
wordpress-development:
adapter: mysql2
encoding: utf8
database: wordpress
pool: 5
username: dev
password: XXXXXX
socket: /var/lib/mysql/mysql.sock
development:
adapter: mysql2
encoding: utf8
database: dev
pool: 5
username: dev
password: XXXXXX
socket: /var/lib/mysql/mysql.sock