There are numerous ways to get a patterns of nodes and relationships and even look up relationships themselves based on relationship properties (e.g. EnrolledIn.where(since: 2002)
but what's the best way to do obtain the relationship based on the specific properties of the nodes. for example
current_user -[:relationship]->event
I know the event ID and so to me, the most logical way is to query the pattern with the event.id as one of the properties being searched. I have something like this right now
event_rel = current_user.events(:e, :rel).where(id: event_id).pluck(:rel)
The above does not work and it returns an array
What you're doing is fine,
pluck(:rel)
will always return an array. If you know you only want one rel, just doIf you're using the master branch from github, you can use
first_rel_to
method, which (along withmatch_to
) is changing the way I'm using the gem lately.The ability to give it an ID was added a couple days ago, it won't work if you're pulling from Rubygems. The version of the method in 3.0.4 doesn't accept an ID, it only accepts a full node. If you happen to have the node loaded, you can do
event_rel = current_user.events.first_rel_to(event)
in the released version.If you don't want to use pluck, you can do
event_rel = current_user.events.where(id: event_id). limit(1).each_rel.first
. Just be aware that that's going to return every rel between those two nodes to Ruby if you omitlimit(1)
, so don't use it unless you know you're only going to get one back. I usually addlimit(1)
when I'm doing this, even if I only think I'm going to get one rel back, cause I like to be safe.I suggest you point your Gemfile at the most recent commit in Github, just read through the new section in the wiki about the changes in 4.0. It's stable and the new features are so cool.