如何正确访问belongs_to模型的属性

发布于 2024-12-26 22:28:37 字数 1087 浏览 3 评论 0 原文

使用以下类及其关联。

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

我可以从 Repository 访问属性(例如:Repository.first.branches.first.note)。

我似乎无法从分支访问属性,从分支获取存储库的名称(例如:Branch.first.repository.first.name)。


** 已解决 ** 事实证明,我实际上无法使用 Repository 作为我的类名,因为 DataMapper 已经使用它 (API)。解决方案是简单地重命名我的类,然后一切都按预期工作。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼藏柔 2025-01-02 22:28:37

您不能使用类名Repository,因为 DataMapper 已使用它(API)。解决方案是简单地重命名该类,然后一切都按预期工作。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文