0

我的网页有些问题。

它运行得很慢,所以我在互联网上读到它可能是对 SQL 的错误使用。所以我评论了更“复杂”的 SQL 行,它又开始顺利运行了。

我的问题是:'有没有办法让这个 SQL 请求“更轻”?

    @companies = Company.where('tbl_companys.state = "enabled"')

    @companies = @companies.includes(:benefit).where("tbl_benefits.end_date >= {Date.today}" )

    @companies = @companies.includes(:benefit).where(tbl_benefits: { state: 'enabled' })

    has_benef_gastro = false

    has_benef_hote = false

    has_benef_ent = false

     until has_benef_gastro == true

        @esta_gastro = (@companies.where('id_category = "2-gastronomia"').shuffle)[0]

        @benefit_gastro = Benefit.where('id_company = ? AND end_date >= ? AND state = "enabled"', @esta_gastro.id_company, Date.today).first 

        if @benefit_gastro.nil? == false

            has_benef_gastro = true

        end

    end

    until has_benef_hote == true

        @esta_hotelero = (@companies.where('id_category = "1-hoteleria"').shuffle)[0]

        @benefit_hote = Benefit.where('id_company = ? AND end_date >= ? AND state = "enabled"', @esta_hotelero.id_company, Date.today).first 

        if @benefit_hote.nil? == false

            has_benef_gastro = true

        end

    end

    until has_benef_ent == true

        @esta_ent = (@companies.where('id_category = "3-entretenimiento"').shuffle)[0]

        @benefit_ent = Benefit.where('id_company = ? AND end_date >= ? AND state = "enabled"', @esta_ent.id_company, Date.today).first 

        if @benefit_ent.nil? == false

            has_benef_gastro = true

        end

    end

谢谢你的帮助 !

4

2 回答 2

0

您每次都在改组@esta_gastro, @esta_hotelero,@esta_ent和变量,这实际上没有任何意义。@benefit_每次执行循环时,它都需要多个新的数据库查询。

如果你想找到一个随机选择,只需在循环之外创建你的集合,洗牌一次(在循环之外),然后迭代这些集合,直到你满足你的条件。

例如:

@esta_gastro = @companies.where('id_category = "2-gastronomia"').shuffle
@benefits = Benefit.where('end_date >= ? AND state = "enabled"', Date.today)
@benefit_gastro = nil
i = 0
until !@benefit_gastro.blank?
  @benefit_gastro = @benefits.where('id_company = ?', @esta_gastro[i].id_company).first
  i += 1
end

编辑

如果整个目标是获得@benefit_gastro定义,那么我什至认为您不需要循环。您可以只定义@esta_gastro集合,然后使用它找到所有对应的好处。因为@esta_gastro是洗牌,你@benefit_gastro会是随机的:

@esta_gastro = @companies.where('id_category = "2-gastronomia"').shuffle
@benefit_gastro = Benefit.where('end_date >= ? AND state = "enabled"', Date.today).where('id_company = ?', @esta_gastro.map(&:id)).limit(1)
于 2013-10-21T23:05:31.430 回答
0

我最终做了一个简单的 SQL 请求,所以我不必为一些 Rails 问题而苦苦挣扎。

不管怎么说,还是要谢谢你 !

于 2013-11-11T13:16:12.687 回答