【问题标题】:Creating Multi-Dimensional Hashes in Ruby From ActiveRecord Results根据 ActiveRecord 结果在 Ruby 中创建多维散列
【发布时间】:2012-06-04 01:54:55
【问题描述】:

我是 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 内部有一个技巧来创建一个至少可以让我接近这个的查询?

【问题讨论】:

  • 我猜你的问题是关于查询范围的。哈希格式重要吗?

标签: ruby-on-rails activerecord rails-models


【解决方案1】:

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

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 %>

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 2011-07-31
    • 1970-01-01
    • 2015-10-11
    • 1970-01-01
    相关资源
    最近更新 更多