Reputation: 1329
Here are my classes, I am following the example provided at: https://github.com/neo4jrb/neo4j/tree/master/example/blog The application so far works for CRUD operations. Here are my model classes:
class Post
include Neo4j::ActiveNode
property :title
property :description
validates :title, presence: true
index :title
has_many :out, :comments, rel_class: PostComment
end
class Comment
include Neo4j::ActiveNode
property :body
index :body
has_one :in, :post, rel_class: PostComment
end
class PostComment
include Neo4j::ActiveRel
from_class Post
to_class Comment
type 'has_comments'
property :created_at
end
I have 2 Posts. Post 1 has 3 Comments and Post 2 has one Comment. For comments in total. When I a run this query from the neo4j-shell I am getting the right number of records.
neo4j-sh (?)$ start n=node(*) match n-[:has_comments]->(m) return n,m;
4 rows
30 ms
This is correct. Now trying something similar form RoR I am getting 8 rows instead of 4.
2.1.5 :012 > result = Post.query_as(:post).match("posts-[:has_comments]->(comment:Comment)").pluck(:post, :comment)
2.1.5 :014 > result.count
=> 8
Can't see what is wrong here. Any help will be much appreciated.
Upvotes: 1
Views: 98
Reputation: 5482
I'd expect 6 rows, not 8, but maybe I'm overlooking something. Doesn't matter, really. Instead of returning post and comment independently, try returning post
and collections of comment
. You don't need query_as
, either, you can do it purely through QueryProxy.
result = Post.as(:post).comments(:comment).pluck(:post, 'collect(comment)')
result.each do |pair|
post = pair[0]
comments_array = pair[1]
comments_array.each do |comment|
# do things
end
end
We're going to have an includes
method in soon that will automate most of this for you, you'll just be able to do Post.all.includes(:comments)
and then post.comments.each
won't result in an extra query.
Also note that the match you wrote in wrote in the shell isn't the same as what the gem is going to generate. Call to_cypher
on your query prior to pluck
to see what it's building. It own't include the return
statement, so add that on: RETURN post, comment
if you want to do it as is. The gem's Cypher is a little messy as of the latest release but it'll be cleaner in the next one.
Upvotes: 1