0

I have these 3 classes:

class Profile < ActiveRecord::Base  
end

class Subject < ActiveRecord::Base
end

class ProfileSubject < ActiveRecord::Base
  belongs_to :profile
  belongs_to :subject

  validates_uniqueness_of :subject_id, scope: :profile_id
end

And this validates_uniqueness_of works great when I update my profile with his associated collection of ProfileSubject. But, on create action - it is not validated this uniqueness. I thought, maybe this is because when I create object I do not have profile_id yet...and I tried add my own token for models, which I can use for connect them and validation by it (use it on scope for validates_uniqueness_of). Ad I know now, it was not useful and not working.

Could you help me...why this standard validation works OK on update action..but does not work on create action.

Creation code is standard, something like this:

    @profile = Profile.new(profile_params)

    if @profile.save
      # ...
    else
      # ...
    end
Arthur Spirke
  • 108
  • 1
  • 12

1 Answers1

-1

Use:

validates_associated :subject, :profile
validates :subject, :profile, :presence => true

In stead of:

validates_uniqueness_of :subject_id, scope: :profile_id
K M Rakibul Islam
  • 33,760
  • 12
  • 89
  • 110
  • I do not need only presence of subject and profile. I need uniqueness of subject in profile scope. In my app means that Profile can has many ProfileSubject and in scope of this profile these ProfileSubjects need to have uniqueness Subjects – Arthur Spirke Aug 31 '15 at 04:51