views:

12

answers:

2

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
A: 

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:

>> p = Person.new(:name => "John Doe")
=> #<Person id: nil, name: "John Doe", created_at: nil, :updated_at: nil>
>> p.new_record?
=> true
>> p.save
=> true
>> p.new_record?
=> false

You can also use built-in rails validations, something like

class Department < ActiveRecord::Base
  validate :my_validation_method, :on => update

  def my_validation_method
    errors.add_to_base("You can't update existing objects")
  end
end

You can find more information on rails validations in the tutorial I linked above.

Nikita Rybak
yup. did not know about validates_uniqueness_of
Omnipresent
A: 

But I guess what you want is to validate that there's only one department with pair user_id = 1, group_id = 22. This could be achieved with:

validates_uniqueness_of :user_id, :scope => [:group_id]
jordinl