0

I have a model called Test that accepts_nested_attributes_for SubTest. A Test basically has an id, and there are multiple SubTests associated with an individual Test.

I want to validate that an attribute of the SubTest is numeric. Here are my models so far.

class Test < ActiveRecord::Base
 has_many :sub_tests
 accepts_nested_attributes_for :sub_tests
end

class SubTest < ActiveRecord::Base
 belongs_to :test
 validates :measurement, :numericality => true, :allow_nil => true
end

Here is the Test controller

def create
     respond_to do |format|
  if @test.save
    flash.now[:notice] = "Test Created"
    format.html { redirect_to(@test) }
    format.xml  { render :xml => @test, :status => :created, :location => @test }
    format.js

  else
    flash.now[:error] = "[Error] Test Not Created Because: #{@test.errors.full_messages.join(", ")}"
    format.html { render :action => "new" }
    format.xml  { render :xml => @test.errors, :status => :unprocessable_entity }
    format.js
  end
end

end

I want the create action in the controller to throw an error if the user enters a non-numeric string in the form for the sub_test.

Currently, if I enter non-numeric values for a sub_test.measurement, Rails doesn't create the Test or SubTest objects (desired behavior). But for some reason no error is thrown, and the Test controller triggers the create.js.erb partial.

I'm getting the impression that the validation for the numericality of sub_test.measurement should actually happen in the Test model, but I'm not sure how to write a custom validation method that tests for numericality.

Thanks in advance!

4

1 に答える 1

0

とった。テスト コントローラーで _error.js.erb パーシャルを指定する必要がありました。

def create
 respond_to do |format|
  if @test.save
   flash.now[:notice] = "Test Created"
   format.html { redirect_to(@test) }
   format.xml  { render :xml => @test, :status => :created, :location => @test }
   format.js

 else
  flash.now[:error] = "[Error] Test Not Created Because: #{@test.errors.full_messages.join(", ")}"
  format.html { render :action => "new" }
  format.xml  { render :xml => @test.errors, :status => :unprocessable_entity }
  format.js { render :partial => 'error' }
 end
end

エラーのパーシャルでは、#messages div を追加しました (ajax を介してフォーム送信を行っているため)。

于 2013-01-16T19:22:05.270 に答える