action when failed 'save'

Rails 3.1.3

I have a model, 'Script' like

class Script < ActiveRecord::Base   belongs_to :video   has_many :users

  validates :startp,   :presence => true,   :uniqueness => true, #HERE!!!!   :numericality => { :only_integer => true, :less_than => 1000}

  validates :script,   :presence => true end

As seen, 'script' has a field 'startp' which is unique. So when users try to save a 'script' having the 'startp' which is identical with that of another 'script', the 'save' action fails. Correct me if I am wrong.

Then, I would like to set up the action upon the failure as follows

  def create     @script =[:script])

    respond_to do |format|       if         format.json { render json: @script, status: :created, location: @script }       else         format.html { redirect_to @script } #HERE!!!! # format.json { render json: @script.errors, status: :unprocessable_entity }       end     end   end

hoping that it will redirect to 'script' page. But it doesnt.

Could anyone point out where I am mistaken?

Thanks in advance.


but after you’re redirecting nowhere… you have to specify something like

redirect_to :controller=> “scripts”, :action=>“index”

Javier Q

I haven’t read it carefully, but If I’m now wrong you just only have to render the new view again

format.html { render action: “new” }

Sorry forgot to mention.

When 'save' action succeeds, it throws json data and catches as Ajax. like

  <%= form_for script, :remote => true do |f| %>

So, when 'save' succeeds, it has no problem.

Does it have anything to do with the case of failure ?


Not really =) I thought you were having trouble with what to show after save :slight_smile:

If there’s an error you just have to render the ‘new’ action again.

format.html { render action: “new” }

Sorry, I misunderstood. When it succeeds, I don't want the page to change.

So, I changed it to

  def create     @script =[:script])     respond_to do |format|       if         format.json { render json: @script, status: :created, location: @script }       else         format.html { render action: "new" }         format.json { render json: @script.errors, status: :unprocessable_entity }       end     end   end

But it doesnt do anything. Of course, data has not been changed at all. Maybe

<%= form_for script, :remote => true do |f| %>

is affecting the failure case as well?


Ahh, with remote true …

In that case you just only have to show an errors div (or an alert), and inside show the @script.errors messages

create.js.erb (That I guess you have)

<% if @script.errors.any? %>

alert(“There’s an error!”);

<% else%>

“Do what you’ve been doing”


Thanks for your help. When I changed the code a bit, a different error is appeared. So I raise another thread. Thanks anyway.