1

我是 Rails 新手,和许多人一样,我似乎在弄清楚 ActiveRecord 和关联如何工作时遇到了挑战。

我有三个模型,用户,项目和任务:

Class User < ActiveRecord::Base
    has_many :projects
    has_many :tasks
end

Class Project < ActiveRecord::Base
    has_many :tasks
    belongs_to :user
end

Class Task < ActiveRecord::Base
    belongs_to :projects
    belongs_to :user
end

Projects 和 Tasks 都有字段user_id。任务有领域project_id

我希望能够通过用户查找所有项目和任务。但是,每次尝试时,即使有项目和任务,我也会得到一个空白数组:

usr = User.find(1)
=> [User id: 1, name: "Some Guy"]
usr.projects
=> []
usr.tasks
=> []

当我通过项目查询任务时,它确实有效:

proj = Project.find(1)
=> [#<Project id: 1, user_id: 1, description: "Some Project">]
proj.tasks
=> [#<Task id: 1, user_id: 1, project_id: 1, description: "Do Something">, 
   #<Task id: 2, user_id: 1, project_id: 1, description: "Do another thing">]

我相信has_manybelongs_to设置是正确的,因为我有其他模型连接到用户并且它们可以正常工作。有什么我想念的想法吗?

4

1 回答 1

1

我通过更改模型关联来解决这个问题。我belongs_to :user从 Task 模型中删除了,并添加了has_many :through与 User 模型的关系:

Class User < ActiveRecord::Base
    has_many :projects
    has_many :tasks, :through => :projects
end

Class Project < ActiveRecord::Base
    has_many :tasks
    belongs_to :user
end

Class Task < ActiveRecord::Base
    belongs_to :projects
end

重新启动控制台后,我现在可以按照我最初尝试的方式提取属于用户的任务:

usr = User.find(1)
usr.projects
=>[#<Project id: 1, user_id: 1, description: "Some Project">]
usr.tasks
=>[#<Task id: 1, project_id: 1, description: "Do Another Thing">]
于 2012-05-30T06:41:32.953 回答