Моделирование WordPress таксономии в ActiveRecord - PullRequest
1 голос
/ 13 сентября 2011

Мне нужно получить доступ к базе данных WordPress в рельсах.Да, веселые времена.Я смог получить доступ к содержанию блога, но мне нужно получить доступ к «категории» для каждого сообщения в блоге.Категории 2 соединения.Необработанный sql для получения этого контента выглядит следующим образом:

select term.name from wp_term_relationships rel
inner join wp_term_taxonomy as tt
on rel.term_taxonomy_id = tt.term_taxonomy_id
inner join wp_terms as term
on term.term_id = tt.term_id
where object_id = 123
and taxonomy = 'category';

У меня уже есть классы WpTerm и WpPost.Теперь мне нужно выяснить, как связать их вместе, используя AR.

Спасибо

Ответы [ 3 ]

1 голос
/ 07 февраля 2013

У меня была та же проблема с отображением модели данных Wordpress в Activerecord.

Ответ Ари Гешера был очень полезен, но я думаю, что ванильный рубиновый класс WPCategory не нужен. Также рассмотрим ERD в Wordpress: Термин имеет много терминов таксономии вместо одной. Так что мои модели Wordpress выглядят так ( обратите внимание, что я использую Rails 2.3 ):

class Term < ActiveRecord::Base
  establish_connection Rails.configuration.database_configuration["wordpress_#{Rails.env}"]
  set_table_name 'wp_terms'
  set_primary_key 'term_id'

  has_many :term_taxonomies
end

class TermTaxonomy < ActiveRecord::Base
  establish_connection Rails.configuration.database_configuration["wordpress_#{Rails.env}"]
  set_table_name 'wp_term_taxonomy'
  set_primary_key 'term_taxonomy_id'

  belongs_to :term
  has_many :term_relationships

  named_scope :categories, :conditions => {:taxonomy => 'category'}
end

class TermRelationship < ActiveRecord::Base
  establish_connection Rails.configuration.database_configuration["wordpress_#{Rails.env}"]
  set_table_name 'wp_term_relationships'
  set_primary_key 'object_id'

  belongs_to :post, :foreign_key => 'object_id'
  belongs_to :term_taxonomy
  has_one :term, :through => :term_taxonomy
end

class Post < ActiveRecord::Base
  establish_connection Rails.configuration.database_configuration["wordpress_#{Rails.env}"]
  set_table_name 'wp_posts'
  set_primary_key 'ID'

  has_many :term_relationships, :foreign_key => 'object_id'
  has_many :term_taxonomies, :through => :term_relationships

  default_scope :conditions => {:post_type => 'post', :post_status => 'publish'}

  def categories
    term_taxonomies.categories.map(&:term)
  end
end

Я заменил WPCategory Ари Гешера на named_scope в TermTaxonomy и метод категорий в Post.

1 голос
/ 01 августа 2012

Это, кажется, работает для меня (я загружаю из 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
0 голосов
/ 31 января 2015

Другой способ:

require 'mysql2'
require 'active_record'
require 'composite_primary_keys'
require 'pry'

spec = {
  adapter:  :mysql2,
  username: :root,
  database: '7fff_com'
}

ActiveRecord::Base.establish_connection(spec)

class Post < ActiveRecord::Base
  self.table_name = 'wp_posts'
  self.primary_key = 'ID'
  has_many :post_term_taxonomies, :foreign_key => :object_id
  has_many :term_taxonomies, through: :post_term_taxonomies

  def categories
    term_taxonomies.where(taxonomy: 'category').map { |t| t.term.name }
  end
  def tags
    term_taxonomies.where(taxonomy: 'post_tag').map { |t| t.term.name }
  end
end

class Term < ActiveRecord::Base
  self.table_name = 'wp_terms'
  self.primary_key = 'term_id'
  has_many :post_term_taxonomies, :foreign_key => :term_taxonomy_id
  has_many :posts, through: :post_term_taxonomies
  has_one :term_taxonomy, primary_key: :term_id
end

class PostTermTaxonomy < ActiveRecord::Base
  self.table_name = 'wp_term_relationships'
  self.primary_keys = :object_id, :term_taxonomy_id
  belongs_to :post, foreign_key: :object_id
  belongs_to :term_taxonomy, foreign_key: :term_taxonomy_id
end

class TermTaxonomy < ActiveRecord::Base
  self.table_name = 'wp_term_taxonomy'
  self.primary_key = 'term_taxonomy_id'
  belongs_to :term
end

Сеанс выглядел бы так:

[1] pry(main)> post = Post.find(764)
[2] pry(main)> post.categories
=> ["Technology", "Code"]
[3] pry(main)> post.tags
=> ["boxen"]

См. http://7fff.com/2015/01/moving-from-wordpress-to-middleman-part-i/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...