在我的控制器中,我想做类似以下的事情:
@book = Book.find(:all, :conditions = > [" created_at > with in the last 1 minute "]
if @book.nil?
# Just incase we didn't create a book, we'll initialize one
@book = Book.create()
end
@chapters = @book.chapters.build etc.............
* 总而言之,当用户上传章节时,如果他们最近创作了一本书,我希望这一章能够自动转到那本书并制作新书。
思考?谢谢大家
答案 0 :(得分:2)
您的代码可能类似
time = Time.now
@book = Book.find(:all, :conditions = > [" created_at >= '#{Time.utc(time.year, time.month, time.day, time.hour, time.min - 1)}'"]) // .first if you're sure that it'll return just one record
if @book.blank? //.blank? not .nil? because the result of find is [] not nil
# Just incase we didn't create a book, we'll initialize one
@book = Array.new() //if you're sure that find'll return just one book you may don't change your code here
@book.first = Book.create()
end
//if you're sure that find'll return just one book you may don't change your code here
@book.each do |book|
@chapters = @book.chapters.build etc.............
end
如果您正在寻找由某个用户创建的图书,则必须将user_id
传递给此方法并且您的条件将
:conditions = > [" created_at >= '?' AND author_id = ?", Time.utc(time.year, time.month, time.day, time.hour, time.min - 1), params[:author_id]])