首页 > 解决方案 > 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 之间创建关系的最佳选项是什么,以及应该在其数据库中退出哪些引用

标签: ruby-on-railsruby-on-rails-5

解决方案


您走在正确的轨道上 - 您需要的只是用户和票证之间的关联以及将其联系在一起的间接关联。

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 中加载的类 - 它可能会产生意想不到的后果。


推荐阅读