0

这是我的模型:

class Hour < ActiveRecord::Base
  attr_accessible :time, :user
  belongs_to :project
end

class Project < ActiveRecord::Base
  attr_accessible :name
  has_many :hour, :dependent => :destroy
end

我正在尝试做这样的事情:

hour = Hour.new
#add values to the hour object here
hour.save!
project = Project.find :first
project.hour.add hour #how do I actually do this?
projet.save!

这会引发错误。如何将模型添加到关联?

我来自 Doctrine2 的 PHP 背景。在 Doctrine2 中,我会执行以下操作:

$projects->getHours()->add($hour);

另外,我已经阅读了这些文档: http: //guides.rubyonrails.org/association_basics.html。它们似乎涵盖了有关如何创建关联的所有内容,但我找不到有关如何使用它们的信息!关于如何使用关联的任何好的文档?

4

2 回答 2

1

首先,正确的名字,

has_many :hours

然后,

project.hours << hour

4.3.1.2 在http://guides.rubyonrails.org/association_basics.html

于 2013-01-02T16:31:53.787 回答
0

您可以像数组一样添加它:

project.hours << hour

但通常感觉更自然的是直接使用关联构建新模型:

hour = project.hours.build({ your: "...",  attributes: "...", here: "..."})
# Do more stuff with hour
project.save!

(该build方法的行为类似于new,但出于技术原因,必须在build此处命名)

或者如果您想立即保存模型:

project.hours.create({ your: "...",  attributes: "...", here: "..."})

Rails 文档列出了关联的“神奇”方法。看看has_many协会参考

于 2013-01-02T16:37:28.217 回答