Rails习惯关系

发布于 2024-08-15 16:11:04 字数 424 浏览 4 评论 0原文

我有 2 个具有 has_and_belongs_to_many 关系的模型:

class Category < ActiveRecord::Base
  has_and_belongs_to_many :templates
end

class Template < ActiveRecord::Base
  has_and_belongs_to_many :categories
end

我想知道如何通过此关系获取类别名称,例如我找到第一个模板:

t = Template.find(:first)

然后使用 t.categories code> 将返回一个对象,但我想要返回category.name,我该如何实现这一点?

I have 2 models which have a has_and_belongs_to_many relation:

class Category < ActiveRecord::Base
  has_and_belongs_to_many :templates
end

class Template < ActiveRecord::Base
  has_and_belongs_to_many :categories
end

I want to know how can I get a category name through this relation, for example I find a first template:

t = Template.find(:first)

Then using t.categories will return an object, but I want to have category.name in return, how can I achieve this?

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

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

发布评论

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

评论(3

许久 2024-08-22 16:11:04

要获取与第一个 Template 实例关联的类别名称,您可以执行以下操作:

Template.first.categories.collect(&:name)

—这使用 Rails 添加的 Symbol#to_proc 支持。更多信息请参见此 Railscast

To get the names of the categories associated with your first Template instance, you can do:

Template.first.categories.collect(&:name)

—This uses the Symbol#to_proc support that Rails adds. More information in this Railscast.

南…巷孤猫 2024-08-22 16:11:04
t.categories.first.name
t.categories.first.name
伴我心暖 2024-08-22 16:11:04

假设类别记录具有名称字段,您可以执行以下操作:

t.categories.map(&:name)

Supposing that a category record has the name field you can do:

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