Uniqueness scope on boolean

Hey, It has been a long time since the last post. I was working in hospitality and running some Java. Now I am employed as a Web Developer.

This week I bring you something  I learned right now.

We are building a Medicine web app. This application consists in medical cases and each case has a bunch of questions and each questions has a bunch of answers, and only one question is correct.
So, in order to the user select only one true answer, I have made a validation with a scope.

# Case Model
class Case < ApplicationRecord
  scope :active, lambda{ |time = Date.today| where("? BETWEEN start_date AND end_date", time) }

  belongs_to :specialty

  has_many :questions, dependent: :destroy
end


# Question model
class Question < ApplicationRecord
  belongs_to :case
  has_many :answers, dependent: :destroy

  has_attached_file :know_more
  do_not_validate_attachment_file_type :know_more
end


#Answer model
class Answer < ApplicationRecord
  belongs_to :question

  validates_uniqueness_of :correct, conditions: -> { where(correct: true) }, scope: :question_id
end
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s