ruby-on-rails - Rails 协会参考资料
问题描述
我正在尝试构建一个小型应用程序来使用 PayPal 出售门票。我们有两种类型的活动门票,标准门票和 VIP 门票。
我想要实现的是当用户访问活动/演出页面时,点击购买门票按钮,然后他被引导到一个支付页面,其中可以选择他想要购买的门票类型,然后结帐。
我对如何设置模型之间的关联感到困惑。
这是我到目前为止所拥有的
class Event < ApplicationRecord
has_many :tickets
end
class Payment < ApplicationRecord
belongs_to :ticket
end
class User < ApplicationRecord
end
class Ticket < ApplicationRecord
enum type: [ :standard, :vip ]
belongs_to :event
end
在 Events、Tickets 和 TicketType 之间创建关系的最佳选项是什么,以及应该在其数据库中退出哪些引用
解决方案
您走在正确的轨道上 - 您需要的只是用户和票证之间的关联以及将其联系在一起的间接关联。
class Event < ApplicationRecord
has_many :tickets
has_many :users, through: :tickets
end
class Payment < ApplicationRecord
belongs_to :ticket
has_one :event, through: :ticket
has_one :user, through: :ticket
end
class User < ApplicationRecord
has_many :tickets
has_many :payments, through: :tickets
has_many :events, through: :tickets
end
class Ticket < ApplicationRecord
enum level: [ :standard, :vip ]
belongs_to :event
belongs_to :user
has_many :payments
end
使用has_many
票证和付款之间的关联是一个很好的选择,因为它可以让您处理跟踪失败的付款。
但是您应该注意type
在 ActiveRecord 中使用枚举或任何其他类型的列的名称,因为它具有特殊意义,因为它用于推断要在多态关联或 STI 中加载的类 - 它可能会产生意想不到的后果。
推荐阅读
- elixir - 如何将流量从 Http 重定向到负载均衡器上用于 SSL 的 Phoenix Elixir 中的 Https?
- python - pytest 夹具传递值
- snmp - 在 snmpd.conf 中使用 Net-SNMP 扩展 PEN 后的 OID 对象
- java - 如何在纯 Java 中诱导触觉反馈
- javascript - 如何确保 Electron 窗口完全从内存中删除?
- angular - Chrome 调试器可以排除 node_modules 文件吗?
- javascript - 对使用 NextJS 和 Express 的 service worker 感到困惑
- python - 对 numpy 二维数组的两个维度使用数组索引
- animation - 使用 Greensock (gsap) 和 Gatsby 反应静态站点错误动画.gsap
- c - c 中的一个简单的 strtod() 示例