這似乎是爲我工作(我從Wordpress作爲輔助數據庫加載,因此establish_connection()
調用和覆蓋table_name
。這應該得到大部分的方式,讓您訪問Wordpress數據作爲ActiveRecord對象。 WordPress的數據我還沒有寫帖子左右(WPPost
)的包裝,使他們更多的用戶從API的角度友好,但是這應該很好地工作的Rails爲基礎的顯示。
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
這裏是我的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
請不要湊齊一些試圖結合你的客戶_wants_的東西,一些可憐的未來維護者將不得不解碼... – 2012-02-14 13:27:43
使用WordPress。沒有意義重新發明輪子。空閒時間將允許您選擇其他可以在您的首選環境中工作的項目。 – MunkiPhD 2012-02-14 13:52:52
你是一個錘子,這不是釘子。有時候你必須告訴客戶「我不是這份工作的合適人選」。當你幫助他們充實項目的需求時,你仍然可以參與項目,並且你可以幫助他們找到一個有能力的PHP人員。然而,將一些可怕的Frankenstinian RoR/Wordpress網站拼湊在一起的想法讓我不寒而慄。 – 2012-02-14 13:58:43