【问题标题】:Rails Associations referencesRails 协会参考资料
【发布时间】:2019-01-25 10:42:31
【问题描述】:

我正在尝试构建一个小型应用程序来使用 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 之间创建关系的最佳选项是什么,以及应该在其数据库中退出哪些引用

【问题讨论】:

  • 我认为最好将工单类型存储为工单模型中的字段。您可以使用枚举器。只需创建一个整数字段 'type' 并在 Ticket 模型中使用 enum type: [:standard, :vip]
  • 我猜Payment 应该是belongs_to :ticket 而不是:event,成为TicketUser 之间的连接表。 Ticket 应该是 belongs_to :event。同意 Vasilisa 的意见,如果门票种类很少,但请考虑将来有更多的选择。
  • 好的,那么用户与事件和门票之间的关系是什么。用户应该有很多票吗?我想在用户购票时将他们的票保存在数据库中?

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


【解决方案1】:

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

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 关联是一个不错的选择,因为它可以让您处理跟踪失败的付款。

但是您应该注意在 ActiveRecord 中将名称 type 用于枚举或任何其他类型的列,因为它具有特殊意义,因为它用于推断要在多态关联或 STI 中加载的类 - 它可以具有意想不到的后果。

【讨论】:

  • 非常感谢。 @最大限度。为事件设置价格的最佳方式是什么,是通过事件表还是通过价格表。那么事件表应该有一个价格列还是门票表应该有一个价格列?我想给用户选择他想购买的票类型的选项。 VIP或标准。那么如何通过枚举记录为事件设置不同的价格
  • 我认为您应该在两者上都放置价格列。如果门票价格波动,您应该跟踪活动的当前价格以及客户为门票支付的费用。哦,记住对列使用十进制类型 - 而不是浮点数。
猜你喜欢
  • 2017-05-29
  • 2011-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多