Rails中通过Account关联创建Expense时自动填充双外键的可行性咨询
Rails中通过Account关联创建Expense时自动填充双外键的可行性咨询
没问题,这完全可以实现!Rails的关联机制其实已经帮我们铺好了路,只需要给Expense模型加个小调整,就能让你通过account.expenses.create()创建费用时,自动填充account_id和user_id,不用手动传user_id。
具体实现方法
最直接的方式是给Expense模型添加一个创建前的回调,让它从关联的Account对象中自动获取User的ID:
class Expense < ApplicationRecord belongs_to :user belongs_to :account # 在创建前自动从关联的account中获取user_id(仅当user_id未手动指定时) before_validation :set_user_from_account, on: :create private def set_user_from_account # 只有当account存在且user_id为空时才赋值 self.user_id ||= account.user_id if account.present? end end
验证效果
现在你就可以像你想要的那样创建Expense了:
account = current_user.accounts.first # 不用传user_id,甚至连account_id都不用传 new_expense = account.expenses.create(amount: 50) # 验证结果 new_expense.account_id == account.id # 返回true new_expense.user_id == current_user.id # 返回true
注意事项
- 确保
Account模型和User模型的关联是正常工作的,也就是account.user能正确返回对应的User对象,不然回调无法获取到user_id。 - 如果你的
expenses表中user_id字段设置了非空约束(NOT NULL),这个回调一定要放在before_validation阶段,这样能在Rails执行数据验证前就填充好user_id,避免验证失败。
这样一来,你就完全不用手动传递user_id,代码也会更简洁直观~
备注:内容来源于stack exchange,提问作者alex
相关产品推荐
相关产品推荐

