开发者

Rails Validation with ActiveModel

开发者 https://www.devze.com 2023-02-08 09:44 出处:网络
I\'ve been going through the documentation for getting ActiveRecord validation working with ActiveModel. For some reason I am not seeing any validation results returned.

I've been going through the documentation for getting ActiveRecord validation working with ActiveModel. For some reason I am not seeing any validation results returned.

I have a set of models which instead of interfacing with ActiveRecord are interfacing through a custom API that will be sitting behind R开发者_高级运维ails.

The Model:

class ApiObject < ApiConnector
  include ActiveModel::Validations
  attr_accessor :fieldName

  validates :fieldName, :presence => true
  def save
    #save method implementation
  end
end

The Controller:

def create
  @apiObject = ApiObject.new(params[:api_object])

  respond_to do |format|
    if @apiObject.save
      format.html { redirect_to(@apiObject, :notice => 'User was successfully created.') }
      format.xml  { render :xml => @apiObject, :status => :created, :location => @apiObject }
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @apiObject.errors, :status => :unprocessable_entity }
    end
  end
end

The Form:

<%= form_for :api_object, :url => '/apiobjectcontroller/' do |f| %>
    <%= f.label :fieldName, 'Field Name' %>
    <%= f.text_field :fieldName %>
    <%= f.submit 'Create'%>
<% end %>

I am following the code laid out here: Rails ActiveModel Validation

The method is correctly returning to the form because @apiObject.save is returning as false, but no validation response is coming back. I've checked the markup and the usual rails validation results are not returned. What am I missing?


I have similar code that works, but I have an initialize method in my classes. Perhaps your model should be:

class ApiObject < ApiConnector
  include ActiveModel::Validations

  validates :fieldName, :presence => true

  attr_accessor :fieldName

  def initialize(fieldName)
    @first_name = fieldName
  end

  def save
    return false unless valid?
    # save method implementation to go here
    # ...
    true # if save successful, otherwise, false
  end
end

If the above works, and you end up having a lot of attributes to assign in your initializer, then you could use this old trick:

def initialize(attributes = {})
  attributes.each do |name, value|
    instance_variable_set "@#{name}", value
  end
end

EDIT: Added a call to valid? in save implementation, so that errors collection will be filled out.


This should fully answer:

http://asciicasts.com/episodes/211-validations-in-rails-3

In a nutshell: create your form with an instance variable + add the necessary code to display your errors.

0

精彩评论

暂无评论...
验证码 换一张
取 消