If I have a model Department with columns user_id and group_id
When the action tries to save an entry into this model that already exists, i.e. 1 (user_id), 22 (group_id) already exists, at that time I want to raise a violation. What is the way to do this in rails?
Following is the code I am using to save right now:
if @department.save
flash[:notice] = "Successfully created department."
redirect_to @department
else
render :action => 'new'
end
Department model
class Department < ActiveRecord::Base
belongs_to :group
belongs_to :user
end
edit
Now, I might have misunderstood you and maybe all you want is validates_uniqueness_of check. Let me know if I miss something.
Active Records has
new_record?method to determine whether object is saved already (whether record in database exists for it).I copy this demo from rails tutorial:
You can also use built-in rails validations, something like
You can find more information on rails validations in the tutorial I linked above.