在验证失败后调用渲染后Rails刷新页面

Kas*_*par 6 ruby-on-rails

所以我有一个控制器动作看起来像这样:

def create
  @term = Term.new(term_params)
  if @term.save
    redirect_to(@term)
  else
    render :new
  end
end
Run Code Online (Sandbox Code Playgroud)

验证失败时,将呈现新的操作视图,用户可以看到所做的错误.问题是,这也会将URL更改为,localhost:3000/terms因此当用户由于某种原因想要刷新页面时,rails会想要将该用户重定向到术语index页面.是否有一种简单的方法可以new term在刷新后让用户保持在页面上?

我实际上没有index页面,terms因为我不需要它,所以在这种情况下这整个情况都会引发错误.

小智 0

实际上有一个修复方法。将resources您的route.rb 文件中的设为resource。这不会创建索引操作,除非您明确要求它,例如:

resources :posts, :only => [:index, :create, :show]
Run Code Online (Sandbox Code Playgroud)

否则,如果您在文件中执行此操作,它将不会生成索引操作routes.rb

resources :posts
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助。