`
xf986321
  • 浏览: 160980 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

在rails环境中直接执行sql语句而不需要创建MODEL

阅读更多

标准格式是:ActiveRecord::Base.connection.execute(sql)

namespace :opengoss do
  desc "USAGES: rake opengoss:collect_rules"
  task :collect_rules => :environment do
    
    
    @collect_rules = CollectRule.find :all
    @collect_rules.each do |rule|
      type = rule.rule_type.to_i
      case type
      when 1
        daily_collect_rule(rule.id)
      when 2
        weekly_collect_rule(rule.id)
      when 3
        monthly_collect_rule(rule.id)
      end   
    end
  end
   
  def daily_collect_rule(id)
    items = CollectRuleItem.find(:all, :conditions => ['collect_rule_id = ?',id.to_i])
    unless items.empty?
      items.each do |item|
        update_aps(id,item)
      end
    end
  end
  
  def weekly_collect_rule(id)
    now = Time.now
    weekly = {'monday' =>1,'tuesday' => 2,'wednesday' => 3 , 'thursday' => 4 , 'friday' => 5 , 'saturday' => 6 ,'sunday' => 0 }
    items = CollectRuleItem.find(:all, :conditions => ['collect_rule_id = ? and start_date = ? ',id.to_i, weekly.index(now.to_date.cwday)])
    unless items.empty?   
      items.each do |item|
        update_aps(id,item)
      end
    end
  end
  
  def monthly_collect_rule(id)
    now = Time.now
    items = CollectRuleItem.find_by_sql("SELECT * FROM `collect_rule_items` WHERE collect_rule_id = #{id}")
    unless items.empty?
      items.each do |item|
        monthly_update_aps(id,item)
      end
    end
  end

  def update_aps(id,item)
    now = Time.now
    con1 = item.start_time < now.hour && item.end_time > now.hour && item.collect_option?
    con2 = (item.start_time >= now.hour || item.end_time <= now.hour ) && !item.collect_option?
    if con1 || con2
      puts "11111"
      ActiveRecord::Base.connection.execute("UPDATE `mit_aps` SET `mit_aps`.`ap_state` = 0  WHERE `mit_aps`.`collect_rule_id` = #{id}") 
    else
      puts "2222"
      ActiveRecord::Base.connection.execute("UPDATE `mit_aps` SET `ap_state` = 2  WHERE `mit_aps`.`collect_rule_id` = #{id}") 
    end
  end
  
  def monthly_update_aps(id,item)
    date = Time.now.to_date
    con1 = item.start_date.to_date < date && item.end_date.to_date > date && item.collect_option?
    con2 = (item.start_date.to_date >= date || item.end_date.to_date <= date ) && !item.collect_option?
    if con1 || con2
      puts "33333"
      ActiveRecord::Base.connection.execute("UPDATE `mit_aps` SET `mit_aps`.`ap_state` = 0  WHERE `mit_aps`.`collect_rule_id` = #{id}") 
    else
      puts "4444"
      ActiveRecord::Base.connection.execute("UPDATE `mit_aps` SET `mit_aps`.`ap_state` = 2  WHERE `mit_aps`.`collect_rule_id` = #{id}") 
    end
  end
  
end
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics