Validation across multiple models

Hi, I’ve a Category model with fields:
*id
*name
*project_id

and class defition:


class Category < ActiveRecord::Base
belongs_to :project
has_many :choices
has_many :voices, :through => :choices
validates_presence_of :project_id, :message => “Selezionare un
progetto.”
end


the other model is Project with fields:

*id
*name
*project_type_id

and class definition


class Project < ActiveRecord::Base
has_many :voices, :order => :name
has_many :categories, :order => :name
belongs_to :project_type
validates_presence_of :name
validates_presence_of :project_type_id

def project_type
  ProjectType.find(project_type_id).name if project_type_id
end

end


What I want is the ability to block category duplication but only when
project_type_id of the project is 2.

I thought I could write something like this in the Category model:
validates_uniqueness_of :name, :scope => :project_id if
Project.find_by_id(3).project_type_id == 2

which indeed works but how can I make dynamic using the project_id of
the current category? I mean I would like to replace
…find_by_id(3)… with something like …find_by_id(project_id)…

As an alternative I’ve tried also defining a validate method in the
Category model but without luck, it always validates or invalidates the
insertions.
Thank you.

Nik

P.s. I’m just learning RoR and OOP so excuse my coding.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs