【问题标题】:Accessing Rest actions in Custom Rake Task在自定义 Rake 任务中访问 Rest 操作
【发布时间】: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


    【解决方案1】:

    Post.new 创建一个新对象,但不会将其持久化到数据库中。您需要使用 Post.create!({:title => post_title, :body => post_body}) 代替。

    Rake 任务不会调用控制器,并且在本地运行的 rake 任务中不会出现强参数。它们可以保护您的应用免受大型、不良互联网的影响。

    【讨论】:

    • 这似乎是朝着正确方向迈出的一步,当然。我已经停止练习,并在早些时候更改为.new。这似乎仍然没有做任何事情。我从终端运行任务,它会等待一两秒钟,然后在控制台或实际应用程序中什么都不输出。想法?
    • 从头开始。你一直很有帮助。它们没有出现在 UI 中,因为它们没有 user_id,这是一个完全不同的编程问题。
    猜你喜欢
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    相关资源
    最近更新 更多