gpt4 book ai didi

ruby-on-rails - rake 任务后增加数组索引

转载 作者:可可西里 更新时间:2023-11-01 11:11:49 25 4
gpt4 key购买 nike

所以我有一个字符串数组,我想将它们发送到我的 Rails 记录器。我想要的是在每次 rake 任务运行后,我的索引增加一个,以便下一个字符串在记录器中发布。我已经尝试过使用类变量和使用 Redis 的传统方法。我的索引拒绝增加。这是我试过的。

尝试 1

accounts_controller.rb

class AccountsController < ApplicationController
cattr_accessor :index
@@index ||= 0

def self.post
current_user = User.find_by(:id => 1)
user_posts = current_user.accounts.find_by(:id => 1).posts
Rails.logger.info user_posts[@@index].tweet
end
end

后 rake

desc 'send post to twitter'
task send_posts: :environment do
AccountsController.post
AccountsController.index += 1
end

在第二次尝试中,我尝试使用 Redis 使我的 @@index 变量持久化。仍然没有增加。

accounts_controller.rb

class AccountsController < ApplicationController
cattr_accessor :index
@@index = $redis.set('index', 0)

def self.post
current_user = User.find_by(:id => 1)
user_posts = current_user.accounts.find_by(:id => 1).posts
Rails.logger.info user_posts[@@index.to_i].tweet
end
end

后 rake

desc 'send post to twitter'
task send_posts: :environment do
AccountsController.post
#AccountsController.index += 1
$redis.incr('index')
end

有人可以帮我在每次 rake 任务运行后遍历数组吗?

最佳答案

为什么不在 rake 任务中循环执行所有这些操作呢?为什么要增加那个变量呢?你可以把它全部放在你的 rake 任务中。

User.find_each do |user|
user_posts = []
user.accounts.each { |account| user_posts << account.posts }
user_posts.each { |post| Rails.logger.info post.tweet }
end

关于ruby-on-rails - rake 任务后增加数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36307740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com