views:

26

answers:

1

Hello,

In my controller I'd like to do something like the following:

@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.............

* In sum, when the user is uploading a chapter, if they've recently created a book, I want the chapter to automatically go to that book and to make a new book.

Thoughts? thank you all

A: 

Hi Your code may be something like

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

if you're looking for a book created by some user you must pass user_id to this method and your conditions'll be

:conditions = > [" created_at >= '?' AND author_id = ?", Time.utc(time.year, time.month, time.day, time.hour, time.min - 1), params[:author_id]])
Bohdan Pohorilets