rails活动模型从同一个表查询父子

时间:2014-02-10 12:24:26

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4

我正在使用以下数据库方案

id    parent     child
1      0          No parent1
2      0          No parent2
3      1          Has parent 1
4      1          Has parent 1
5      2          Has parent 2

将上表视为我的表架构,现在我该如何查询或使用它来显示这样的内容

No parent1
    * Has parent 1
    * Has parent 1
No parent2
    * Has parent 2

这是我目前的控制器

@locations = Location.all.order(parent: :asc)

任何人都可以给我一个建议我该怎么做

3 个答案:

答案 0 :(得分:1)

您始终可以使用group_by。此外,这是指向related question的链接。

答案 1 :(得分:1)

您正在实施父子关系。请参阅此question

模型应该是这样的

class Location < ActiveRecord::Base
  has_many :childrens, :class_name => "Location"
  belongs_to :parent, :class_name => "Location" 
end

在您的位置表中添加parent_idchild_id字段。

然后拨打@locations = Location.parents

@locations.each{|location|
 location.name
 Childrens:
 location.childrens.each{|child|
  child.name
 }
}

答案 2 :(得分:1)

我解决了下面的描述:

模型/ location.rb

@echo on

REM Read list of files
(FOR /F "usebackq delims=" %%G IN ("d:\cifs\fslit.txt") DO (
    REM output all files to a single combined file
    TYPE "%%~G"
))>combined.txt
REM Call out to function to remove duplicates from file.
CALL :DEDUPE "combined.txt"
GOTO :EOF

:DEDUPE
:: Remove duplicates from file
setlocal disableDelayedExpansion
set "file=%~1"
set "sorted=%file%.sorted"
set "deduped=%file%.deduped"
::Define a variable containing a linefeed character
set LF=^


::The 2 blank lines above are critical, do not remove
sort "%file%" >"%sorted%"
>"%deduped%" (
  set "prev="
  for /f usebackq^ eol^=^%LF%%LF%^ delims^= %%A in ("%sorted%") do (
    set "ln=%%A"
    setlocal enableDelayedExpansion
    if /i "!ln!" neq "!prev!" (
      endlocal
      (echo %%A)
      set "prev=%%A"
    ) else endlocal
  )
)
>nul move /y "%deduped%" "%file%"
del "%sorted%"
GOTO :EOF

locations_controller.rb

  has_many :childrens, class_name: 'Location', foreign_key: :parent
  belongs_to :parent,  class_name: 'Location', foreign_key: :id

  def self.order_by_parent(top: nil)
    locations = Location.where(parent: top)

    locations_return = []
    locations.each do |location|
      locations_return << location
      auxs = Location.order_by_parent(top: location.id)
      auxs.each do |aux|
        locations_return << aux
      end
    end
    locations_return
  end