0

我对 Rails 比较陌生,对数据库操作也很陌生。

我正在尝试在数据库中创建一个类,其中包含许多自定义对象。这些自定义对象也将存储在数据库中的单独表中。我设法将其设置如下

class MyClass < ActiveRecord::Base
  has_many :other_objects, :dependent => destroy
end

class OtherObject < ActiveRecord::Base
  belongs_to :my_class
  attr_accessible :some_stuff...
end

我已经创建了适当的数据库表并设法让它工作。

现在我想做的是在我的类中有(四个)“OtherObject”的特定实例,可以通过一些简单的标识符来访问,比如

test = MyClass.new
...
test.instance_of_other_object.some_attribute = "blahblah"

这样就可以更新关联对象的数据库条目。解决此问题的最佳方法是什么?

4

3 回答 3

1

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_objectselected_other_object=方法,因此您不必自己定义这些。

于 2013-02-18T11:48:18.523 回答
0

现在用于object.duprails 3.1 及更高版本。

a = MyClass.first # finds the first instance of the model "MyClass"  

b = a.dup # duplicates the record.

c = a.dup # duplicates the record again.  

b.field_name = "blahblah"

c.fielf_name = "blahblah"

b.save # saves the record into the database for object b.

c.save # saves the record into the database for object c.

如果您查看您的数据库,您可以看到已经创建了一条新记录。它与第一条记录相同,只是它有一个新的 id

另请检查复制模型以获取有关它的更多信息。

于 2013-02-18T14:50:53.593 回答
0

这不是一个完整的答案,但我想出了一些适用于获取对象的方法,但不适用于设置它。

class MyClass < ActiveRecord::Base
  has_many :other_objects, :dependent => destroy

  def particular_instance
    return OtherObject.find_by_id(self.particular_instance_id)
  end
end

我的数据库架构看起来像这样

create_table "my_classs", :force => true do |t|
  t.integer "particular_instance_id"
end

create_table "other_objects", :force => true do |t|
  t.integer "my_class_id"
  t.string "some_attribute"
end

更新 为了设置 other_object 类的属性,可以使用 update_attributes 方法

my_class.particular_instance.update_attributes(:some_attribute => "blah")
于 2013-02-18T12:04:32.270 回答