Ruby on rails Rails-根据时间戳查找或创建?可能的
在我的控制器中,我希望执行以下操作:Ruby on rails Rails-根据时间戳查找或创建?可能的,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,在我的控制器中,我希望执行以下操作: @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 e
@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.............
*总之,当用户上传章节时,如果他们最近创建了一本书,我希望该章节自动转到该书并生成一本新书
想法?谢谢大家您好,您的代码可能类似
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\u id
传递给此方法,您的条件将是
:conditions = > [" created_at >= '?' AND author_id = ?", Time.utc(time.year, time.month, time.day, time.hour, time.min - 1), params[:author_id]])