2017-07-26 121 views
0

模型之间的关系列出的:如何查询rails的方式? Rails的3.2

class ErrorScope < ActiveRecord::Base 
    belongs_to :server 
    has_many :scope_to_fixflow_map 
    attr_accessible :id, :server_id, :error_codes, :scoping_method, :priority, :error_codes_is_wildcard_match 
    serialize :error_codes 
    ..... 
end 

class ScopeToFixflowMap < ActiveRecord::Base 
    belongs_to :error_scope 
    attr_accessible :id, :server_id, :error_scope_id, :path, :fixflow_class_name 
    ...... 
end 

class Server < ActiveRecord::Base 
    has_many :error_scopes 
    ...... 
end 

schema.rb

create_table "error_scopes", :force => true do |t| 
    t.integer "server_id",      :limit => 8,     :null => false 
    t.text "error_codes",             :null => false 
    t.text "scoping_method" 
    t.integer "priority",              :null => false 
    t.boolean "error_codes_is_wildcard_match",    :default => false 
    end 

    create_table "scope_to_fixflow_maps", :force => true do |t| 
    t.integer "server_id",   :limit => 8, :null => false 
    t.integer "error_scope_id",  :limit => 8, :null => false 
    t.string "path" 
    t.string "fixflow_class_name",    :null => false 
    end 

现在我有一个SQL查询,这给了我想要的输出:

SELECT fixflow_class_name 
FROM error_scopes s 
join scope_to_fixflow_maps m on s.id=m.error_scope_id 
join servers serv on serv.id=s.server_id 
where error_codes regexp 'error_scope_test' 
and path = 'x' 
and assettag = 'y' 

我想什么事这么远。使用它的工作原理

ErrorScope.where("error_codes like ?", "%error_scope_test\n%").select {|tag| tag.server.assettag == "y"}[0].scope_to_fixflow_map.select {|y| y.path == "x"}[0].fixflow_class_name 

加入

ErrorScope.joins(:server, :scope_to_fixflow_map).where("error_codes LIKE ?", "%error_scope_test%").select {|tag| tag.server.assettag == "y"}[0].scope_to_fixflow_map.select {|y| y.path == "x"}[0].fixflow_class_name 

我相信一定有更好的方法来做到这一点?查询

+0

这是从SQL不明哪些表格引用您正在引用的各个列。 –

回答

1

事情是这样的工作:

ErrorScope.joins(:server, :scope_to_fixflow_map) 
.where("error_codes LIKE ?", "%error_scope_test%") 
.where("servers.assettag='y'") 
.where("scope_to_fixflow_maps.path='x'") 
.select("scope_to_fixflow_maps.fixflow_class_name") 
+0

'ErrorScope.joins(:server,:scope_to_fixflow_map).where(“error_codes LIKE?”,“%error_scope_test%”)'这很好。当我链接这个'.where(“server.assettag ='y'”)'给我错误。 ActiveRecord :: StatementInvalid:Mysql2 :: Error:'where子句'中的未知列'server.assettag':' – Kavincat

+0

@Kavincat是的,应该是'servers'&'scope_to_fixflow_maps'而不是'server'&'scope_to_fixflow_map'分别。更新了答案。 –

+0

我使用'pluck'而不是'select'。有效。 – Kavincat

0

不是轨道的方式,但快速和肮脏的:

ActiveRecord::Base.execute("SELECT fixflow_class_name 
FROM error_scopes s 
join scope_to_fixflow_maps m on s.id=m.error_scope_id 
join servers serv on serv.id=s.server_id 
where error_codes regexp 'error_scope_test' 
and path = 'x' 
and assettag = 'y'") 

返回哈希的数组,你可以用