Let's say I have the following association with an attached condition:
belongs_to :admin_user, :class_name => 'User', :foreign_key => :admin_user_id, :conditions=> 'users.admin=TRUE'
The doc API states that the: conditions parameter on the __to property will be:
Indicate the conditions under which the related object must match the order of being included as a WHERE SQL fragment, such as resolved = 1.
But the output does not display the WHERE clause on select, and in any case, I would expect conditions like this on the assign_to function to prevent this relationship from starting, starting with INSERT, not SELECT. This parameter does not seem to affect the belongs_to association, unless I see something. The option makes sense on has_many, I just don’t see how this relates to belongs_to.
EDIT: Further research shows that you can really maintain a connection that violates the condition, but you cannot get a related record after reloading the record.
In a class defined like this:
class Widget < ActiveRecord::Base belongs_to :big_bloop, :class_name => "Bloop", :foreign_key => :big_bloop_id, :conditions => ["big_bloop = ?", true] belongs_to :bloop, :conditions => ["big_bloop = ?", true] end
... from the console we see:
>> bloop = Bloop.new => #<Bloop id: nil, name: nil, big_bloop: nil> >> widget = Widget.new => #<Widget id: nil, name: nil, bloop_id: nil, big_bloop_id: nil> >> widget.bloop = bloop => #<Bloop id: nil, name: nil, big_bloop: nil> >> widget.save! => true >> widget => #<Widget id: 2, name: nil, bloop_id: 2, big_bloop_id: nil>
I tied a bloop that violated the condition and saved it. The connection is saved in db (see Bloop_id and big_bloop_id in the last line above).
>> big_bloop = Bloop.new => #<Bloop id: nil, name: nil, big_bloop: nil> >> widget.big_bloop = big_bloop => #<Bloop id: nil, name: nil, big_bloop: nil> >> widget.save! => true >> widget => #<Widget id: 2, name: nil, bloop_id: 2, big_bloop_id: 3>
Same thing, different attribute.
>> widget.bloop => #<Bloop id: 2, name: nil, big_bloop: nil> >> widget.big_bloop => #<Bloop id: 3, name: nil, big_bloop: nil>
Both invalid bloops remain in memory.
>> widget.reload => #<Widget id: 2, name: nil, bloop_id: 2, big_bloop_id: 3> >> widget.bloop => nil >> widget.big_bloop => nil
After the reboot, they disappeared because the SELECT statement really uses the WHERE clause to exclude them.
Bloop Load (0.3ms) SELECT * FROM `bloops` WHERE (`bloops`.`id` = 2 AND (big_bloop = 1))
And still the widget still has links:
>> widget => #<Widget id: 2, name: nil, bloop_id: 2, big_bloop_id: 3>
Seems strange to me, but there you go.