我有一个数据结构,其中的主题有子主题,它们也有子主题,从原始主题继续向下关于六个级别。每个主题都有多个子主题。 我正在寻找一种方法来遍历这些数据,并从每个子主题中提取附属的数据......就像拉取我想要的“下游”数据一样。遍历Rails应用程序中的复杂数据结构
For example Given a topic structure:
Harry_Potter > Characters > Slitherin_House.videos
(假设slitherin房子对于每个成员,马尔福,克拉布等的副标题)我要为每位成员的视频出现在Slitherin_House,字符和Harry_Potter视频列表(每个祖先)。
我一直环顾四周,整个Ancestry和Acts As Tree跌跌撞撞地通过代码阅读并试着在使用它们,但他们似乎周围事物的祖先方面更加注重,而不是访问,并从拉数据儿童。
我也试过我的手在使用协会
has_many :through, and has_and_belongs_to_many
但在我试图创建一个工作遍历系统已经失败。似乎无法完成包装我的头如何做到这一点。
有没有人有什么想法或建议做什么给予这样的困境?或者知道提供任何此类功能的宝石?
关系类&模式:(因为它应该流像小溪)
class CreateStreams < ActiveRecord::Migration
def change
create_table :streams do |t|
t.integer :downstream_id
t.integer :upstream_id
t.timestamps
end
add_index :streams, :downstream_id
add_index :streams, :upstream_id
add_index :streams, [:downstream_id, :upstream_id], unique: true
end
end
# == Schema Information
#
# Table name: streams
#
# id :integer not null, primary key
# downstream_id :integer
# upstream_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Stream < ActiveRecord::Base
attr_accessible :downstream_id
belongs_to :subsidiary, class_name: "Topic"
belongs_to :tributary, class_name: "Topic"
validates :downstream_id, presence: true
validates :upstream_id, presence: true
end
主题模型的
# == Schema Information
#
# Table name: topics
#
# id :integer not null, primary key
# name :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# slug :string(255)
# wiki :string(255)
# summary :string(255)
class Topic < ActiveRecord::Base
extend FriendlyId
attr_accessible :name, :wiki, :summary
has_many :streams, foreign_key: "downstream_id", dependent: :destroy
has_many :tributaries, through: :streams, source: :tributary
has_many :reverse_streams, foreign_key: "upstream_id",
class_name: "Stream",
dependent: :destroy
has_many :subsidiaries, :through => :reverse_streams, source: :subsidiary
friendly_id :name, use: :slugged
validates :name, presence: true, length: { maximum: 50 },
uniqueness: { case_sensitive: false }
def downstream?(other_topic)
streams.find_by_downstream_id(other_topic.id)
end
def flow!(other_topic)
streams.create!(downstream_id: other_topic.id)
end
def dam!(other_topic)
streams.find_by_downstream_id(other_topic.id).destroy
end
end
注:我也希望能够指定一个副主题,多的父母。例如,角色可能会置于“演员”之下。
你可以显示你的模型和表格的来源? – 2012-04-08 17:57:18
添加主题模型和流(关系)模型/表 我可以添加主题表以及它虽然分散在多个迁移,所以我添加了注释版本 – 2012-04-08 19:29:33