1

我承认我不完全知道为什么前置过滤器是(或者即使它是)处理我的问题的最佳方法,但我被一位开发人员告诉过,他对 Rails 的了解比我多得多编程就是这样。所以我要努力让它发挥作用!

所以我要做的是检查数据库中的最新一本书是否是在 7 天或更早之前创建的,如果是,则创建一个新的。

这是我的图书控制器目前的样子:

class BooksController < ApplicationController
  before_filter :check_seven_days, :only => [:create]

...

def create
    @book = Book.new(params[:book])

    respond_to do |format|
      if @book.save
        format.html { redirect_to user_url(@book.user), notice: 'Book was successfully added to your queue.' }
        format.json { render json: @book, status: :created, location: @book }
      else
        format.html { render action: "new" }
        format.json { render json: @book.errors, status: :unprocessable_entity }
      end
    end
  end

...

protected
        def check_seven_days
            @user = User.find(params[:id])

            @not_queued_books = @user.books.not_queued

            @not_queued_books.each do |book|
                Book.new if book.created_at >= 7.days.ago
            end
        end


end

然而,这并不完全有效......根本。before 过滤器中的代码或多或少是伪代码。我们会这样称呼它,因为我还在学习如何正确地编写 Ruby!但希望你能明白我想要做的事情:)

而且,你可以看到这是从哪里来的,我在模型中使用范围来检查一本书是否在 25 秒前被添加:

scope :queued, lambda { where('created_at > ?', 25.seconds.ago) }
  scope :not_queued, lambda { where('created_at <= ?', 25.seconds.ago) }
  scope :date_desc, order("created_at DESC")

此外,视图循环(在用户显示视图中)如下所示:

<% @not_queued_books.date_desc.each do |book| %>
    <%= book.title %>
    <%= book.author %>
<% end %>
4

1 回答 1

1

Book.new 只是实例化一个新的 Book 对象,不保存也不带任何参数;你的意思:

Book.create(params[:book])

?

于 2012-12-31T00:19:40.477 回答