2017-05-17 7 views
0

恐ろしいネストされたセットは、先祖のインスタンスメソッドが含まれています https://github.com/collectiveidea/awesome_nested_set/wiki/Awesome-nested-set-cheat-sheet素晴らしいnestsetセット上位クラスのメソッド

@john = Group.where(name: "John").first 
@tree = @john.ancestors 

私は「ジョンと呼ばれるグループごとに先祖の配列やARの関係を返すクラスメソッドを探しています"

@johns = Group.where(name: "John") 
@tree = @johns.ancestors 

現在、私はAR関係をループし、各行に対してインスタンスメソッドを実行しています。

アップデート1

class Group < ApplicationRecord 
    acts_as_nested_set :counter_cache => :children_count 

    def self.build_tree(groups) 
    groups.collect(&:ancestors).flatten! 
    end 
end 

class GroupsController < ApplicationController 
    def index 
     @johns = Group.where(name: "John") 
     @tree = Group.build_tree(@johns) 
    end 
end 

エラー:

undefined method `collect' for #<Class:0x00000002a28378> 

アップデート2

祖先=>グループの関係に問題があるように見えます。あなたは、ほとんど存在し

class Group < ApplicationRecord 
    acts_as_nested_set :counter_cache => :children_count 
    has_many :ancestors 

    def self.build_tree(objects) 
    objects.collect(&:ancestors).flatten! 
    end 
End 

class Ancestor < ActiveRecord::Base 
    belongs_to :group 
    scope :with_group, -> (name) { joins(:group).where("groups.name = ?", name) } 
end 


2.4.0 :008 > Ancestor.joins(:group) 
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation "ancestors" does not exist 
LINE 1: SELECT "ancestors".* FROM "ancestors" INNER JOIN "groups" O... 
           ^
: SELECT "ancestors".* FROM "ancestors" INNER JOIN "groups" ON "groups"."id" = "ancestors"."group_id" LIMIT $1 


2.4.0 :009 > Ancestor.includes(:group) 
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation "ancestors" does not exist 
LINE 1: SELECT "ancestors".* FROM "ancestors" LIMIT $1 
           ^
: SELECT "ancestors".* FROM "ancestors" LIMIT $1 

答えて

1

は、

@johns = People.where(name: "John") 
@tree = @johns.collect(&:ancestors).flatten! 

を次試すか、あなただけのレコードを渡すことができ、あなたのコードベースよると、クエリに

Ancestor.joins(:people).where("peoples.name = ?", 'John') 

に参加使用することができますが、これではありません良い方法。 scope

class People < ActiveRecord::Base 
    acts_as_nested_set :counter_cache => :children_count 

    def self.build_tree(peoples) 
    peoples.collect(&:ancestors).flatten! 
    end 
end 


class PeopleController < ApplicationController 
    def index 
     @johns = People.where(name: "John") 
     @tree = People.build_tree(@johns) 
    end 
end 

例、アメージング1

class People < ActiveRecord::Base 
    has_many :ancestors 
    #your codes goes here 
end 


class Ancestor < ActiveRecord::Base 
    belongs_to :people 
    scope :with_people, -> (name) { joins(:people).where("peoples.name = ?", name) } 
end 


class PeopleController < ApplicationController 
    def index 
     @tree = Ancestor.with_people("John") 
    end 
end 
+0

良い、ありがとうございました。最初のソリューションをPeopleモデルのクラスメソッドとして定義できますか? "未定義のメソッド' collect '"エラーが発生します。私のコードを表示するために私の例を更新します。 – Dercni

+0

私はあなたのコードを修正するために私の答えを編集しましたが、これは良い方法ではない、あなたはスコープを使用することができます、スコープで例を追加します。 –

+0

どうすればいいですか? –