Rails查询产生不正确的结果

时间:2015-06-10 08:06:04

标签: ruby-on-rails ruby

我在rails应用程序中有两个表,如下所示:

ActiveRecord::Schema.define(version: 20150603200530) do  
  create_table "relationships", force: true do |t|
    t.integer "source"
    t.integer "target"
    t.integer "value"
  end

  create_table "users", force: true do |t|
    t.string  "name"
    t.integer "group"
  end
end

一个用户有很多关系(User.id = relationship.source)。

我使用populate.rake文件

按如下方式填充数据库
namespace :db do
  desc "Erase and fill database"
  task :populate => :environment do
    require 'populator'
    require 'faker'

    [User, Relationship].each(&:delete_all)



   User.populate 5 do |user|
      user.name = Populator.words(1..3).titleize
      user.group =1..5
    Relationship.populate 1..5 do |relationship|
        relationship.source = rand(1..5)
        relationship.target = rand(1..5)
        relationship.value = rand(1..5)
        end
    end
  end

我正在尝试将数据库查询结果转换为json的特定格式(实际的json格式化在其他地方完成),这要求名称和组位于' node' &链接'下的来源,目标和价值。在我的用户模型中,我按如下方式查询了数据库。

class User < ActiveRecord::Base
    has_many :relationships

  def self.including_relationships
    User.joins("INNER JOIN relationships ON users.id = relationships.source").select("users.name, users.`group`, relationships.source, relationships.target, relationships.value").each_with_object(Hash.new{|h, k| h[k] = []}) do |a, obj| 


      obj['nodes'] << a.slice('name','group')
      obj['links'] << a.slice('source', 'target', 'value')
    end
  end
end

这会产生可用的json输出。 each_with_object部分之前的查询工作正常,并在rails控制台中给出了预期的结果。但是当我在浏览器中运行它时,它产生的名称数量不正确。我认为问题必须在于数组的工作方式,因为查询很好,但我得到的节点和链接太多了。 rails控制台的查询输出位于:

[#,#,#,#,#,#,#,#,#,#,#,#,#,#]

我目前得到的json输出在这里:

{"nodes":[{"name":"A Voluptatem Quo","group":2},{"name":"Debitis Ut","group":1},{"name":"A Voluptatem Quo","group":2},{"name":"Eos","group":1},{"name":"Eos","group":1},{"name":"Debitis Ut","group":1},{"name":"Debitis Ut","group":1},{"name":"Placeat Aliquam Cumque","group":5},{"name":"Placeat Aliquam Cumque","group":5},{"name":"Placeat Aliquam Cumque","group":5},{"name":"Debitis Ut","group":1},{"name":"Error In","group":4},{"name":"Eos","group":1},{"name":"A Voluptatem Quo","group":2}],"links":[{"source":1,"target":1,"value":4},{"source":4,"target":1,"value":4},{"source":1,"target":3,"value":4},{"source":3,"target":5,"value":2},{"source":3,"target":5,"value":4},{"source":4,"target":1,"value":5},{"source":4,"target":5,"value":1},{"source":5,"target":5,"value":2},{"source":5,"target":5,"value":1},{"source":5,"target":3,"value":5},{"source":4,"target":4,"value":3},{"source":2,"target":2,"value":5},{"source":3,"target":1,"value":5},{"source":1,"target":5,"value":2}]}

0 个答案:

没有答案