Kevin Jalbert
Kevin Jalbert

Reputation: 3245

How to properly access a belongs_to model's properties

Using the following classes and their associations.

class Repository
  include DataMapper::Resource
  property :id, Serial
  property :name, String
  has n, :branches
end

class Branch
  include DataMapper::Resource
  property :id, Serial
  property :note, String
  belongs_to :repository
end

# Simple creation of a repository and branch belonging to said repository
repo = Repository.new
repo.name = "Bob"
branch = repo.branches.new
branch.note = "Example Note"
repo.save

# Print the repo->branch's note
puts repo.branches.first.note  # Prints "Example Note"

# Print the branch->repo name
puts branch.repository.first.name  # Does not work
puts branch.repository.name  # Does not work

I can access properties down from Repository (ex: Repository.first.branches.first.note).

I cannot seem to access properties up from Branch, getting the repository's name from a branch (ex: Branch.first.repository.first.name).


** SOLVED ** Turns out that I cannot actual use Repository as my class name as DataMapper already uses it (API). Solution is to simply rename my class and then it all works as intended.

Upvotes: 1

Views: 432

Answers (1)

Kevin Jalbert
Kevin Jalbert

Reputation: 3245

You cannot use the class name Repository as DataMapper already uses it (API). Solution is to simply rename the class and then it all works as intended.

Upvotes: 2

Related Questions