Ruby 在自定义Rake任务中访问Rest操作
我有一个运行在Rails 4.1中的小型博客应用程序。它允许用户登录,然后创建、编辑和删除带有标题和正文的基本帖子。这一切都完美地通过用户界面运行 我正在尝试编写一个定制的rake任务,稍后将附加到chron作业以自动创建帖子。现在我有这个:Ruby 在自定义Rake任务中访问Rest操作,ruby,ruby-on-rails-4,automation,rake,Ruby,Ruby On Rails 4,Automation,Rake,我有一个运行在Rails 4.1中的小型博客应用程序。它允许用户登录,然后创建、编辑和删除带有标题和正文的基本帖子。这一切都完美地通过用户界面运行 我正在尝试编写一个定制的rake任务,稍后将附加到chron作业以自动创建帖子。现在我有这个: namespace :blog do desc "Automatically post to all users accounts" task auto_post: :environment do post_title = "Automated
namespace :blog do
desc "Automatically post to all users accounts"
task auto_post: :environment do
post_title = "Automated Blog Post Title"
post_body = "Hello World!"
Post.create!({:title => post_title,
:body => post_body})
end
end
据我所知,它有适当的名称空间等,可以使用rake blog:auto_post运行。Post的控制器如下所示:
class PostsController < ApplicationController
def index
@posts = current_user.posts
end
def new
@post = Post.new
end
def create
@post = Post.new post_params
if @post.save
current_user.posts << @post
flash[:notice] = "New post created!"
redirect_to posts_path
else
render 'new'
end
end
def edit
@post = Post.find params[:id]
end
.....
private
def post_params
params.require(:post).permit(:title, :body)
end
end
据我所知,我应该能够将我的:title和:body传递给Post.newaction并让它工作。我怀疑我没有正确地与强参数交互。谁能帮我澄清一下吗
编辑:我的psql显示点击数据库的帖子,所以我很接近。但不确定它们为什么没有出现在应用程序界面中。Post.new创建一个新对象,但不会将其持久化到数据库中。你需要使用Post.create!{:title=>post_title,:body=>post_body}
Rake任务不调用控制器,并且在本地运行的Rake任务中不会出现强参数。它们是用来保护你的应用程序不受大而坏的互联网的影响。这似乎是朝着正确的方向迈出的一步。我已经不练了,在早些时候换成了新的。但这似乎仍然没有任何作用。我从终端运行该任务,它停留一两秒钟,然后在控制台或实际应用程序中不输出任何内容。想法?把这一切都划掉。你帮了大忙。它们没有出现在UI中,因为它们没有用户id,这是一个完全不同的编程问题。