ActiveRecord :: RecordNotSaved - 强制嵌套重定向

时间:2013-10-20 11:12:25

标签: ruby-on-rails nested

早上好,

在花了大部分时间搞清楚如何限制我的模特创作后,我终于到了某个地方。嵌套语句现在告诉我没有保存这是个好消息。

但是我似乎无法让重定向或flash [:base]工作。以下是代码:

class SnippetsController < ApplicationController
  before_filter :find_book

   def create
   if @snippet = @book.snippets.create!(params[:snippet])
      redirect_to @book
    else
      flash[:base]
      #render 
   end
 end     


def approve
   #@snippet = @book.snippet.find(params[:id])
    if @snippet.update_attribute(:approved, true)
    redirect_to users_path
  else
   render root_path
  end 
end

  def edit
    @snippet = @book.snippets.find(params[:id])
  end    

  def update
    @snippet = @book.snippets.find(params[:id])

    respond_to do |format|
      if @snippet.update_attributes(params[:snippet])
        format.html { redirect_to @book, notice: 'Comment was successfully updated.' }
      else
        format.html { render action: "edit" }
      end
    end
  end

  private

  def find_book

    @book = Book.find(params[:book_id])
  end
end

模型父(书)

class Book < ActiveRecord::Base
  has_many :snippets
  attr_accessible :title, :book_id, :size

  def snippets_limit_reached?
   if size == 0
    self.snippets.count >= 2
    elsif size == 1
       self.snippets.count >= 3
     elsif size == 2
       self.snippets.count >= 4
     else
       return false
  end
 end
end

儿童(片段)

class Snippet < ActiveRecord::Base
  before_create :check_limit
  belongs_to :book
   attr_accessible :content, :book_id 

  validates :book_id, presence: true


    def check_limit         
      if book.snippets_limit_reached?
        errors.add :base, 'Snippet limit reached.'           
        return false
      end       
      return true
    end 
end

如果您还需要其他任何东西,请告诉我,只要它在运行时我无法通过嵌套创建!

if @snippet = @book.snippets.create!(params[:snippet])

1 个答案:

答案 0 :(得分:0)

Bang方法(创建!,保存!)在不成功时抛出错误,而不是返回,评估为false。

删除爆炸可以解决这个问题。