我是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
项目和任务都有字段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_many
和belongs_to
设置是正确的,因为我有其他模型连接到用户并且它们正常工作。我缺少什么想法?
答案 0 :(得分:1)
我通过改变模型关联来解决这个问题。我从任务模型中删除了belongs_to :user
,并为用户模型添加了has_many :through
关系:
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">]