Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8246917
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T22:39:59+00:00 2026-06-07T22:39:59+00:00

I have a variable value that is initialized when I create a new object.

  • 0

I have a variable value that is initialized when I create a new object. However, this variable is not a column of my table. I just want to use it inside my model and have it available for some methods inside my class:

class MyClass < ActiveRecord::Base
  def initialize (value)
    @value = value
  end
end

So, when a create a new object @value will keep the some text temporarily, for example:

test = MyClass.new("some text")

There is a way to validates the variable value to accept only text?

class MyClass < ActiveRecord::Base
  validates_format_of :value => /^\w+$/ # it doesn't work

  def initialize (value)
    @value = value
  end
end

EDIT

I have tried all the answer, but my Rspec is still passing:

My new class:

class MyClass < ActiveRecord::Base
  validate :check_value

  def check_value
    errors.add(:base,"value is wrong") and return false if !@value || !@value.match(/^\w+$/)
  end  

  def initialize (value)
    @value = value
  end

  def mymethod
    @value
  end
end

My Rspec (I was expecting it to fail, but it is still passing):

describe MyClass do
  it 'checking the value' do
    @test = MyClass.new('1111').mymethod
    @test.should == '1111'
  end
end

I would like to raise an validation error before assigning 1111 to the @value.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T22:40:01+00:00Added an answer on June 7, 2026 at 10:40 pm

    Rails does the validations only if you call valid? or save on the model. So if you want it to accept only values for your value when calling those methods, do a custom validation:

    class MyClass < ActiveRecord::Base
    
      validate :value_string
    
      #further code
    

    Setup your value validation like that under the protected scope

    protected
    
      def value_string
        self.errors[:base] << 'Please assign a string to value' unless @value.match(/^\w+$/)
      end
    

    These validations won’t be called without calling valid?or save, like I said before.
    If you want value not to be assigned with another value than a word-like-value at any time, there’s no other way than to prevent it on initialization:

    def initialize(attributes = nil, options = {})
      attr_value = attributes.delete(:value) if attributes
      @value = attr_value if attr_value && attr_value.match(/^\w+$/)
    
      super
    end
    

    EDIT

    I would not recommend raising an ActiveRecord validation error when assigning not accepted values on initialization. Try to raise your own custom error based on ArgumentError

    Outside your class

    YourError = Class.new(ArgumentError)
    

    Inside your Class

    def initialize(attributes = nil, options = {})
      attr_value = attributes.delete(:value) if attributes
      if attr_value && attr_value.match(/^\w+$/)
        @value = attr_value
      elsif attr_value
        raise YourError.new('Value only accepts words')
      end
    
      super
    end
    

    and then test it like this

    describe Myclass do
      it 'should raise an error if value is assigned with something else than a word' do
        lambda{ MyClass.new(:value => 1111)}.should raise_error(YourError)
      end
      it 'should assign the value for words' do
        MyClass.new(:value => 'word').value.should == 'word'
      end
    end
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i have value in php variable like that $var='2.500000550'; echo $var what i want
I have a member variable that tells units for a value I have measured
I have a file that defines constant variables, like this: define_vars.php <? define(something,value); define(something1,value);
I have a variable of unknown value, it will be an integer. For this
I have a JSON file and want to parse value of variable second value
I have a variable newItem. I want to place the value stored in newItem
Imagine such situation that I have a function like this: Object f() { Object
i have a loop where a variable value will change in each loop and
I have controller and model. i am modifying a variable value in a model,
I have a variable when i write its value using document.write() i don't get

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.