# Strange behaviour with ActiveRecord and collection\_ids

**URL:** <https://www.ruby-forum.com/t/strange-behaviour-with-activerecord-and-collection-ids/176450>\
**Category:** Rails\
**Created:** [September 30, 2009, 6:02pm UTC](https://www.ruby-forum.com/t/strange-behaviour-with-activerecord-and-collection-ids/176450 "2009-09-30T18:02:18Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![MaurSSS\_cio\_Szabo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/c67d28/32.png) [@MaurSSS\_cio\_Szabo](https://www.ruby-forum.com/u/MaurSSS_cio_Szabo)\
**Post date:** [September 30, 2009, 6:02pm UTC](https://www.ruby-forum.com/t/strange-behaviour-with-activerecord-and-collection-ids/176450/1 "2009-09-30T18:02:18Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![MaurSSS\_cio\_Szabo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/c67d28/32.png) [@MaurSSS\_cio\_Szabo](https://www.ruby-forum.com/u/MaurSSS_cio_Szabo)\
**Post date:** [October 3, 2009, 1:28am UTC](https://www.ruby-forum.com/t/strange-behaviour-with-activerecord-and-collection-ids/176450/2 "2009-10-03T01:28:46Z")

</div>

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?
