【问题标题】:How to show results based on sql result data如何根据sql结果数据显示结果
【发布时间】: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


    【解决方案1】:

    将静态方法(或范围,如果您愿意)添加到您的 Tag 模型:

    app/models/tag_hierarchy.rb

    class TagHierarchy
      belongs_to :tag, foreign_key: :ancestor_id
    end
    

    app/models/tag.rb

    class Tag
      has_many :tag_hierarchies, foreign_key: :ancestor_id
    
      def self.descendants(id = nil)
        id ||= 0
        self.where(id: id).joins(:tag_hierarchies).where(tag_hierarchies: {generations: 1})
      end
    end
    

    创建一个控制器:

    rake g controller TagsController

    将代码添加到您的控制器:

    app/controllers/tags_controller.rb

    class TagsController < ApplicationController
      def index
        @descendants = Tag.descendants
      end
    
      def show
        @descendants = Tag.descendants(params[:id])
      end
    end
    

    然后使用视图中的所有内容:

    app/views/tags/show.html.erb

    <div class="row">
      <div class="span6 offset3">
        <%= @descendants.each do |tag| %>
            <%= link_to tag.name, tag %>
            <%# you can also use tag.tag_hierarchies here %>
        <% end %>
      </div>
    </div>
    

    我建议你阅读一些关于 Rails 的教程和/或文档:

    Active Record Associations

    Rails Routing from the Outside In

    Getting Started with Rails

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多