3

I'm trying to figure out how to define these owner/member relationships in my Neo4j.rb Active::Node models.

  • Users can create many teams (and become the "owner" of those teams)
  • Users can fetch the teams that they have created
  • Teams have a single owner (user) and many members (other users)
  • Owners can add other users as members to a team
  • Users can fetch all teams that they are either an owner or a member of

So far I have something like this, but it isn't working right and I am totally lost.

class User
  include Neo4j::ActiveNode
  has_many :out, :my_teams, model_class: 'Team'
end

class Team
  include Neo4j::ActiveNode
  property :name, type: String
  has_one :in, :owner, model_class: 'User'
end

user = create(:user)
team = build(:team)
user.my_teams << team
expect(team.owner).to eq user
Andrew
  • 227,796
  • 193
  • 515
  • 708

1 Answers1

4

Firstly you should make sure you're using 5.0.0 of the gems which were just released yesterday (yay!)

Secondly (and you should get error messages about this when you upgrade), you should be specifying a type option for your associations, like this:

class User
  include Neo4j::ActiveNode
  has_many :out, :my_teams, type: :OWNS_TEAM, model_class: 'Team'
end

That tells ActiveNode which relationship types to use for creation and querying.

Lastly, for creation you use class methods on the model classes like this:

user = User.create
team = Team.create

user.my_teams << team

On a somewhat picky personal note, I'd also suggest an association name of teams or owned_teams because it creates methods which you use to get those teams from the user object.

Brian Underwood
  • 10,746
  • 1
  • 22
  • 34
  • Thanks. I still have some questions...what is the point of defining the type of relationship? How is it used? How do I know which direction the relationship flows? Seems it could go either way. – Andrew Jun 23 '15 at 05:49
  • Also you mention that I should simply call it teams. But I wonder how to define the relationship of a user who is a member of a team. I'd like to be able to call `.teams` to get both teams that I've created as well as the teams that I am a member of. – Andrew Jun 23 '15 at 05:51
  • WRT the `type` option, it defines the `type` (kind of like the label) or the relationship in Neo4j. This can be whatever you want and yes, it can definitely go either way. That's part of Neo4j's schemaless relationship nature is that it's up to you to decide how you want to model – Brian Underwood Jun 24 '15 at 02:18
  • As far as getting teams that you're both owner of and a member of, I don't think it's currently possible to define multiple relationship types for an association (though we maybe should support that). You could define associations for both and then call `user.owned_teams + user.teams`. In some cases it might make sense for every owner to also be a member and so you would have two relationships between the same nodes – Brian Underwood Jun 24 '15 at 02:21