2

belongs_to在 Rails 的概念中有一些我不太了解的东西。文档指出:

Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object

假设我有一个Employee实体:

class Employee < ActiveRecord::Base  
  belongs_to :department
  belongs_to :city    
  belongs_to :pay_grade
end

以下代码会触发三个更新吗?如果是,有更好的方法吗?:

e = Employee.create("John Smith")
Department.find(1) << e
City.find(42) << e
Pay_Grade.find("P-78") << e
4

1 回答 1

3

您可以简单地分配它:

e = Employee.new(:name => "John Smith")
e.department = Department.find(1)
e.city = City.find(42)
e.pay_grade = Pay_Grade.where(:name => "P-78")

e.save

在保存对象之前,我将其更改create为构造对象。new构造函数采用散列,而不是不同的值。find只接受 id 而不是字符串,where而是在字段上使用。

您还可以使用以下内容:

Employee.create(:name => "John Smith", 
                :department => Department.find(1), 
                :city => City.find(42), 
                :pay_grade => PayGrade.where(:name => "P-78").first

另请注意,型号名称应为驼峰式:PayGrade而不是Pay_Grade.

于 2012-09-12T15:45:34.017 回答