mysql - 如何查询rails方式?轨道3.2

标签 mysql sql ruby ruby-on-rails-3 activerecord

模型之间的关系列表:

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/

相关文章:

php - FPDF 和 While 循环

mysql - 如何使用流畅的 api 在 EF6 中映射值对象标识?

mysql - 选择具有日期和文章点的行(无关系)

sql - 为什么此查询针对不同的日期格式返回不同的结果?

ruby-on-rails - 处理 API 速率限制?

ruby - 如何从数组 Ruby 中删除括号和引号

ruby-on-rails - 如何在不使用 form_for 和模型实例的情况下在 Rails 中创建表单?

javascript - Sequelize "model.associate"属性不再起作用?

php - INSERT维护检查表表格PHP HTML MYSQL

sql - 在数据库上拥有多语言数据的最佳方式