0

我是 Rails 新手,在用 ActiveRecord 搞清楚一些事情时遇到了麻烦。

现在,我有三个模型:

class Project < ActiveRecord::Base
    attr_accessible :name
    has_and_belongs_to_many :tags
    has_many :tasks
end

class Task < ActiveRecord::Base
    attr_accessible :todo
    has_and_belongs_to_many :tags
    has_many :tasks
end

class Tag < ActiveRecord::Base
    attr_accesible :description
    has_and_belongs_to_many :projects
    has_and_belongs_to_many :tasks
end

我正在尝试创建一个返回属于特定标签的任务的哈希,以便:

Project_Tasks = { 1 => { project.name, "tasks" => { "task 1", "task 2", "task 3" } 
                  2 => { project.name, "tasks" => { "task 1", "task 2", "task 3" } }

我不太确定如何创建它。我的第一个倾向是在其中一个类中创建一个方法(我已经在哪个类上来回走动......现在,我认为它最好在“标签”下提供)循环通过与给定标签匹配的项目, 查询匹配两者的任务并将它们附加到数组中。

迄今为止,这还没有奏效。我完全被难住了。

关于我如何做到这一点的任何想法?一种方法是合适的方法,还是在 ActiveRecord 中有一个技巧来创建一个至少可以让我接近这个的查询?

4

1 回答 1

0

我已尝试修复您的模型定义。

class Project < ActiveRecord::Base
    attr_accessible :name
    has_and_belongs_to_many :tags
    has_many :tasks
end

class Task < ActiveRecord::Base
    attr_accessible :todo
    has_and_belongs_to_many :tags
    belongs_to :project
end

class Tag < ActiveRecord::Base
    attr_accesible :description
    has_and_belongs_to_many :projects
    has_and_belongs_to_many :tasks
end

现在您应该能够访问特定项目的数据(在控制器中),如下所示:

@project = Project.find_by_id(1)  # Loaded a project
@tasks = @project.tasks  # all task for this project in an array

要在视图中显示它:

<%= @project.name %><br />
<% @tasks.each do |task| %>
  <%= task.todo %><br />
<% end %>

我希望这有帮助

于 2012-06-04T02:13:38.780 回答