该has_many
关联设置MyClass#other_objects
(和一堆其他方法)允许您轻松处理关联记录。
你可能想要:
my_class.other_objects.each do |other_object|
other_object.update_attributes(:foo => 'bar')
end
如果要直接更新 SQL,可以使用update_all
:
my_class.other_objects.update_all(:foo => 'bar')
更新:
如果这是您需要的那种关联,您可以定义一个belongs_to
关联:
class MyClass < ActiveRecord::Base
has_many :other_objects, :dependent => :destroy
# uses :selected_other_object_id
belongs_to :selected_other_object, :class_name => "OtherObject"
end
my_class = MyClass.first
my_class.selected_other_object = other_object # Set the object.
# => #<OtherClass:...>
my_class.selected_other_object_id # ID has been set.
# => 10
my_class.selected_other_object # Retrieve the object.
# => #<OtherClass:...>
my_class.selected_other_object.save # Persist ID and other fields in the DB.
my_class = MyClass.find(my_class.id) # If you fetch the object again...
# => #<MyClass:...>
my_class.selected_other_object_id # The ID is still there.
# => 10
my_class.selected_other_object # You have the ID, you get the object.
# => #<OtherClass:...>
my_class.selected_other_object.foo = "bar" # Access associated object this way.
another_variable = my_class.selected_other_object # Or this way.
但是请记住,这并不假定它:selected_other_object
是 的子集:other_objects
。
另请注意,设置关联时已经设置了selected_other_object
和selected_other_object=
方法,因此您不必自己定义这些。