事件和票证上的Rails关联逻辑

时间:2015-08-03 12:23:22

标签: database ruby-on-rails-4 activerecord associations

我正在使用ruby on rails编写一个事件应用程序,我仍然坚持如何有效地进行关联:该关联基于以下表User,Event,Ticket。我现在遇到的问题是门票和活动,它们是两种类型的门票:免费和付出也有数量。

如果有人能帮助我这个协会,我将很高兴。

1 个答案:

答案 0 :(得分:0)

关于故障单类型的类型,您应该查看STI

先决条件:

# Gemfile
gem 'active_record_union'

它基本上是这样的:

class Ticket
end

class FreeTicket < Ticket
  # Free-ticket stuff goes here
end

class PaidTicket < Ticket
  validates :price, presence: true # and other paid-related checks
end

我建议在这些方面提供一些关联:

class Event # Also STI
end
class FreeEvent < Event
  has_many :free_tickets
  has_many :users, through: :free_tickets
end
class PaidEvent < Event
  has_many :paid_tickets
  has_many :users, through: :paid_tickets
end
class Ticket
  belongs_to :event
  belongs_to :user
  scope :open, -> { where(user_id: nil) }
  scope :taken, -> { where.not(user_id: nil) }
end
class User
  has_many :free_tickets
  has_many :paid_tickets
  has_many :free_events, through :free_tickets
  has_many :paid_events, through :paid_tickets

  def events
    free_events.union(paid_events)
  end
end

通过这种方式,您可以执行以下操作:

Event.find(1).tickets.count # => 13
Event.find(1).tickets.open.count # => 10
Event.find(1).tickets.taken.count # => 3
Event.find(1).users.count # => 3
User.find(1).events.count # => 1
User.find(1).free_events.count # => 0
User.find(1).paid_events.count # => 1