【发布时间】:2015-08-01 17:40:46
【问题描述】:
我在我的新网站中使用了闭包树的想法。 在其中一个显示视图中,我想按 id(1 级后代)选择数据,或者如果 id 为空,则第一级。 设置结果如何连接sql?
查询:
select id,name
from tags t
join tag_hierarchies th (t.id = th.ancestor_id)
where t.id=nvl(?,0) and th.generations=1
到目前为止的代码(app/views/show.erb 上的问题):
db/schema.rb:
create_table "tags" do |t|
t.string "name", :null=>false
t.boolean "isCat", :default => true
end
create_table "tag_hierarchies", :id => false do |t|
t.integer "ancestor_id", :null => true
t.integer "descendant_id", :null => false
t.integer "generations", :null => false
end
add_foreign_key(:tag_hierarchies, :tags, :column => 'ancestor_id')
add_foreign_key(:tag_hierarchies, :tags, :column => 'descendant_id')
app/models/tag.rb
class Tag < ActiveRecord::Base
#attr_accessible :name, :isCat
validates :name, uniqueness: false, allow_blank: false
end
app/models/Tag_Hierarchie.rb
class TagHierarchie < ActiveRecord::Base
#attr_accessible :ancestor_id, :descendant_id, :generations
end
app/views/show.erb
<% provide(:title, category_name_or_constant(@tags)) %>
<h1><%= category_name_or_constant(@tags)%></h1>
<div class="row">
<div class="span6 offset3">
<%= for(<<here goes the sql by the Closure tree >>) do |f| %>
<%= link_to tag.name, tag %>
<% end %>
</div>
</div>
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 model-view-controller