validation - Rails & Primary Keys / Uniqueness. How do you use multiple columns for a primary key? -
my question quite identical 1 (multicolumn primary keys in rails) i'm still not understanding 100%.
let's have model visit
visits id room_id date created_at updated_at
in case, want (room_id, date) 'primary key'. now, post saying don't need change primary key, jus add uniqueness validations , stuff?
so need
add_index :visits, [:room_id, :date]
or
add_index :visits, [:id, :room_id] add_index :visits, [:id, :date]
? tie each column want in 'primary key' :id latter code, or put desired columns []'s former code.
also, how do validations? don't want either of :room_id or :date unique, combination. how do in rails?
according previous question, right 1 is:
add_index :visits, [:room_id, :date], :unique => true
this piece of code prevents database inserting room_id
same date
. in terms of model validation, need add:
validates_uniqueness_of :date, :scope => :room_id
this way, activerecord
can , validate record before trying insert.
p.s.: change date
column name more specific start_date
, creation_date
, etc. believe cause potential problems in future.
Comments
Post a Comment