Arif Arif - 3 months ago 11
SQL Question

Table column partially dependent on another column? [Rails]

I want to have two type

:boolean
columns, let's say X and Y, where Y is partially dependent on X. When X is true, Y can be either true or false, but when X is false, Y must be false. Is this possible?

class AddPrivacyColumnsToPosts < ActiveRecord::Migration
def change
add_column("posts", "public", :boolean, :default => true)
add_column("posts", "collectable", :boolean, :default => true)
end
end


where
public
is X, and
collectable
is Y, i.e. only public posts can be collected. If a post is set to private (when
public
is false), then
collectable
should automatically be set to false.

Answer

I would add a before save call back to Post

before_save :set_collectable 

def set_collectable 
  if !public? 
    self.collectable = false 
  end
end