【发布时间】:2014-07-15 14:05:33
【问题描述】:
我有一个在 Rails 4.1 中运行的小型博客应用程序。它允许用户登录,然后创建、编辑和删除带有标题和正文的基本帖子。这一切都通过用户界面完美运行。
我正在尝试编写自定义 rake 任务(稍后将附加到 chron 作业)以自动创建帖子。现在我有这个:
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.new 操作并让它工作。我怀疑我没有正确地与强参数交互。谁能帮我解决这个问题。
编辑:我的 psql 显示访问数据库的帖子,所以我很接近。不知道为什么它们没有出现在应用界面中。
【问题讨论】:
标签: ruby ruby-on-rails-4 automation rake