Shailesh Tainwala
Shailesh Tainwala

Reputation: 6507

Rails validation - confirming presence of form attribute that is not saved in model

My application has a form_for tag with element :foo that is not saved in the model for the object used in form_for.

I need to confirm that the user submitted a value for this element, using Rails Validation Helpers. However, the 'presence' validator makes a call to object.foo to confirm that it has a value. Since foo is not saved as part of my object, how can I do this validation?

Thanks!

Upvotes: 0

Views: 2437

Answers (2)

doctororange
doctororange

Reputation: 11810

You should probably check for the presence of it in the params in your controller action:

def create
  @model = MyModel.find(params[:id])
  unless params[:foo].present?
    @model.errors.add(:foo, "You need more foo")
  end

  # ...
end

If :foo is an attribute of your object that isn't saved in the database and you really want to use ActiveRecord Validations, you can create an attr_accessor for it, and validate presence like this.

class MyModel < ActiveRecord::Base
  attr_accessor :foo
  validates :foo, presence: true
end

But that could result in invalid records being saved, so you probably don't want to do it this way.

Upvotes: 2

Thaha kp
Thaha kp

Reputation: 3709

Try this..

class SearchController < ApplicationController
  include ActiveModel::ForbiddenAttributesProtection

  def create
    # Doesn't have to be an ActiveRecord model
    @results = Search.create(search_params)
    respond_with @results
  end

  private

  def search_params
    # This will ensure that you have :start_time and :end_time, but will allow :foo and :bar
    params.require(:val1, :foo).permit(:foo, :bar , whatever else)
  end
end

class Search < ActiveRecord::Base
  validates :presence_of_foo

  private

  def presence_of_foo
    errors.add(:foo, "should be foo") if (foo.empty?) 
  end
end

See more here

Upvotes: 1

Related Questions