calico-cat
calico-cat

Reputation: 1322

How to constrain db elements in rails?

I have four tables in my db Movie, Showing, Ticket and Purchase. A Movie has many Showings, a Showing has many Tickets and a Purchase has many Tickets.

I'd like to constrain it so that all the Tickets in the Purchase can only be for exactly one Movie. I'm new to Rails and wondered if there was a way to do this in the Model. (validate or something similar)

Upvotes: 0

Views: 42

Answers (2)

bratsche
bratsche

Reputation: 2674

class Purchase
  validate :validate_same_movie

  private

  def validate_same_movie
    movie_ids = tickets.map do |ticket|
      ticket.showing.movie.id
    end.uniq

    errors[:base] << "Can't have more than one movie in a purchase." if movie_ids.length > 1
  end
end

Something along these lines.

But I would also urge you to think about exactly why you're introducing this additional complexity into your system. In my experience, I typically buy movie tickets for the same movie at once and I don't recall when I've bought tickets for different movies in a single purchase. But just because I haven't done it doesn't mean nobody does. You're adding complexity and you're reducing functionality of your site. I'm not saying you don't have a valid reason, because I don't know what your app is.. but just a suggestion that you might think about if you really need this.

Upvotes: 1

t56k
t56k

Reputation: 6981

What about something like this?

class Purchase < ActiveRecord::Base
  has_one :movie
  has_many :tickets
end

class Ticket < ActiveRecord::Base
  has_one :purchase
end

class Movie < ActiveRecord::Base
  has_many :purchases
end

Upvotes: 0

Related Questions