【发布时间】:2019-08-19 16:34:03
【问题描述】:
我正在考虑创建一个方法,该方法将给我来自 Active::Record::Associations::CollectionProxy 的特定对象。
例如,我有一个用户模型,它有许多 user_checklists 和 user_checklists belongs_to checklist 模型。所以我想创建一个方法来检查清单模型中的值并从 user_checklist 模型中返回值。
例如。 checklists 表有以下一行
╔═════════════════════╦══════════════════╗
║ id ║ name ║
╠═════════════════════╬══════════════════╣
║ 1 ║ Complete MBA ║
╠═════════════════════╬══════════════════╣
║ 2 ║ Painting class ║
╚═════════════════════╩══════════════════╝
用户表有以下内容
╔═════════════════════╦══════════════════╗
║ id ║ name ║
╠═════════════════════╬══════════════════╣
║ 1 ║ name ║
╚═════════════════════╩══════════════════╝
user_checklist 有以下一行
╔════════════╦════════════╦═══════════════╦═══════════════╗
║ id ║ user_id ║ checklist_id ║ completed ║
╠════════════╬════════════╬═══════════════╬═══════════════╣
║ 1 ║ 1 ║ 1 ║ true ║
╠════════════╬════════════╬═══════════════╬═══════════════╣
║ 2 ║ 1 ║ 2 ║ false ║
╚════════════╩════════════╩═══════════════╩═══════════════╝
所以我想在 user_checklist 中创建一个名为 MBA 的方法,它可以为我提供 MBA 完成值。
我想这样称呼
user.first.user_checklists.mba.completed
我不知道如何实现这一点。还是我在这里完全想错了?
【问题讨论】:
-
您是否需要一种方法来返回用户是否完成了清单(任何清单)或仅特定值(MBA)@gsumk?
-
具体值。在这种情况下,我浪费了
completed MBA@Aarthi 的价值
标签: ruby-on-rails activerecord rails-activerecord