Strange behaviour with ActiveRecord and collection_ids

Hello, I don’t exactly know if this can be considered a bug, but before
posting it as a bug I’d like to see if there is a workaround

In my application, I have a couple of students and the subjects (matter
subjects) they choose. So far, I have 3 models:

class Student < ActiveRecord::Base
has_many :options
has_many :subjects, :through => :options
end

class Option < ActiveRecord::Base
belongs_to :student
belongs_to :subject
end

class Subject < ActiveRecord::Base
has_many :options
has_many :students, :through => :options
end

But, the problem is, not every student can choose any subject. So, I
have a
couple of validations in the Student model (in my program, actually,
things
are a bit more complicated), but there is a serious problem with this
approach: when I do, for example:

@student = Student.first
@student.subject_ids = [1, 2]

On the second line, ActiveRecord saves the associations on the
database
(but doesn’t runs the Student validations), so I end with a invalid
student.
Is there a way to stop ActiveRecord from doing this?

Thanks in advance.

Ok, I’ve seen on the rails documentation, it says clearly that what
I’m doing woudn’t work. But, in DataMapper, I can set the value of,
say, @student.subjects and be sure it would just commit the changes to
the database when I save the model. Is this possible in ActiveRecord
too?

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