基本Rails帮助(迭代)

时间:2014-05-21 13:17:27

标签: ruby-on-rails

我基本上只希望这个脚本能够为用户拥有的每个节目运行其名称,即user_show模型。这是我到目前为止(下面是我遇到麻烦的部分)。

class Show < ActiveRecord::Base
  require 'nokogiri'
  require 'open-uri'

  has_many :user_shows
  has_many :users, through: :user_shows



  def self.search(search)  
    if search  
      where('title LIKE ?', "%#{search}%")  
    else  
      scoped  
    end  
  end 

 def self.update_all_screenings
   UserShow.select(:show_id) do |show|
    show.update_attribute(:next_screening, Show.update_next_screening(Show.select(:url)))
  end

end

  def self.update_next_screening(url)
    nextep = Nokogiri::HTML(open(url))
    ## Finds the title of the show and extracts the date of the show and converts to string ##
    begin

        title = nextep.at_css('h1').text
        date = nextep.at_css('.next_episode .highlight_date').text[/\d{1,2}\/\d{1,2}\/\d{4}/]
        date = date.to_s

    ## Because if it airs today it won't have a date rather a time this checks whether or not 
    ## there is a date. If there is it will remain, if not it will insert todays date
    ## plus get the time that the show is airing    
        if date =~ /\d{1,2}\/\d{1,2}\/\d{4}/
            showtime = DateTime.strptime(date, "%m/%d/%Y")
        else
            date = DateTime.now.strftime("%D")
            time = nextep.at_css('.next_episode .highlight_date').text[/\dPM|\dAM/]
            time = time.to_s
            showtime = date + " " + time
            showtime = DateTime.strptime(showtime, "%m/%d/%y %l%p")

        end

        return showtime

    rescue
        return nil
    end
  end
end

这是不起作用的部分

def self.update_all_screenings
       UserShow.select(:show_id) do |show|
        show.update_attribute(:next_screening, Show.update_next_screening(Show.select(:url)))
      end

    end

所以基本上我希望它遍历每个user_show,提取show_id然后在该节目上执行脚本。

1 个答案:

答案 0 :(得分:1)

在这之前你没有.each它不是循环的正确语法,因为你从UserShow中选择了show_id,你正在迭代UserShow不显示的实例。

def self.update_all_screenings
  #get ids of unique shows belonging to users
  shows_with_users = UserShow.pluck("DISTINCT show_id")

  #get the Shows and loop
  Show.where(id: shows_with_users).each do |show|
    show.update_attribute(:next_screening, Show.update_next_screening(show.url))
  end
end

我假设您希望基于其余代码进行此操作。当我迭代show的实例时,我可以使用show.url。我不明白为什么你在下一次筛选类方法时更新了。

相关问题