模型之间的关系列表:
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
架构.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
我确信一定有更好的方法来执行此查询?
最佳答案
类似这样的事情:
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")
关于mysql - 如何查询rails方式?轨道3.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45331305/