ruby-on-rails - 每次在rails 5.1上自动创建父对象时如何生成子对象
问题描述
在我的应用程序中,我有以下模型:
class Bus < ApplicationRecord
belongs_to :user
has_many :seats, dependent: :destroy
end
class Seat < ApplicationRecord
belongs_to :bus
end
有没有办法在每次用户添加公共汽车时创建特定数量的“座位”?我不希望用户为公共汽车创造座位。
解决方案
您可以将子对象的创建挂钩到after_create
回调
https://guides.rubyonrails.org/active_record_callbacks.html
class Parent < ApplicationRecord
# register callback
after_create :createChilds
private
def createChilds
# create required amount of childs
end
end
推荐阅读
- javascript - 映射的下拉菜单不会显示在最前面
- java - 没有正确排序
- google-cloud-firestore - 添加 Firestore 索引是否会导致每个现有文档的读取操作?
- google-apps-script - Google Scripts - 使用带有 .getRange() 函数的变量?
- kubernetes - 将 YAML 转换为 JSON 时出错:yaml:第 13 行:未找到预期的密钥
- aws-lambda - 如何在 aws 中创建自定义 REST API 端点?
- javascript - 即使在表格中呈现时包含值,对象值也为空
- non-ascii-characters - 如果域包含非 ASCI 字符为“ö”,我收到错误“站点所有者错误:站点密钥的域无效”。我应该怎么办?
- solidity - ABI 编码 Etherscan 验证问题 (err_code_2)
- python - 机器人框架确保唯一的测试用例名称