I am trying to validate the input of a state field using:
include ActionView::Helpers
class Credentials < ActiveRecord::Base
attr_accessible :license_number, ...:address_zip_code,
...
validates :license_number, presence: true, length: { minimum: 4 }
...
validates_inclusion_of :current_practice_address_state, :in => state_list
end
The variable state_list is an array described in helpers/credentials_helper.rb
Testing the model I run into undefined local variable error
$ bundle exec rspec spec/models/credentials_spec.rb
in `method_missing': undefined local variable or method `state_list' for #<Class:0x007f86a1844250> (NameError)
The helper class looks like:
module CredentialsHelper
state_list = %w(AL AK...WY)
end
Your call to include has to be inside the class:
class Credentials < ActiveRecord::Base
include ActionView::Helpers
...
end
Related
I'm trying to abstract generic functions to a model concern on a Rails 5 with Mongoid app. This is the first app I do with mongoid and with other projects I had no problems implementing the next:
movie.rb
class Movie
include Mongoid::Document
include Genericable
field :name, type: String
field :year, type: Date
field :length, type: Integer
field :writers, type: Array
validates_presence_of :name, :year, :length
validates_uniqueness_of :name
index({name: 1}, {unique: true})
has_many :writers, class_name: "Person"
embeds_many :roles, class_name: "MovieRole"
end
genericable.rb (concern)
module Genericable
extend ActiveSupport::Concern
def self.s
all.map{|x| x}
end
end
(Methods are for demonstration purposes only).
When I try, on my rails console Movie.s I get next error:
NoMethodError: undefined method `s' for Movie:Class
Any clue about what I'm doing wrong? Thanks in advance for any help.
I am using virtus(1.0.5) with rails (5.0.2). I am using Virtus for a model since it has validations based on the page being accessed.
My Organization model is as
class Organization < ApplicationRecord
validates :name, presence: true
end
and form created using virtus is as
class OrganizationProfileForm
include ActiveModel::Model
include Virtus.model
attribute :call_center_number, String, default: :org_call_center_number
validates :call_center_number, presence: true
def initialize(organization)
#organization = organization
end
private
def org_call_center_number
#organization.call_center_number
end
end
Unfortunately, the above code doesn't work
Loading development environment (Rails 5.0.2)
2.3.0 :001 > of = OrganizationProfileForm.new(Organization.last)
Organization Load (0.6ms) SELECT "organizations".* FROM "organizations" ORDER BY "organizations"."id" DESC LIMIT $1 [["LIMIT", 1]]
=> #<OrganizationProfileForm:0x007f9d61edd6a8 #organization=# <Organization id: 1, name: "Some name", call_center_number: "4892374928", created_at: "2017-03-29 09:35:22", updated_at: "2017-03-29 09:37:59">>
2.3.0 :002 > of.call_center_number
=> nil
We need to call super() in the initialize method.
Try removing the line private, as this may be preventing the call to the method org_call_center_number. The example given for default values on the Virtus repo uses a public instance method, not a private one.
See: What are the differences between "private", "public", and "protected methods"?
I'm running Rails 3.2.13 and Ruby 2.1.0.
This error has popped up in a seemingly random fashion. I only have one Location class in my app. But I did add several new gems recently: Rmagick, CarrierWave and CarrierWave-Azure.
Here's the error:
TypeError in CompaniesController#show
superclass mismatch for class Location
app/models/location.rb:1:in `<top (required)>'
app/controllers/companies_controller.rb:24:in `show'
If I go to companies_controller.rb ln 24 there is this code:
#addresses = #company.addresses
Line 23: actually references Location:
#locations = #company.locations
If I step through the code in debug mode the #locations variable isn't created anymore when line 23 executes, all other variables prior to line 23 are created. I haven't touched this code in months, the only recent additions to the codebase have revolved around the gems I listed above but did not include changes to Location.rb, Company.rb, Address.rb or Companies_Controller.
Anyone know what's going on here? thx!
Update:
Here is my Location model:
class Location < ActiveRecord::Base
attr_accessible :address_attributes, :address, :created_by, :is_active, :location_name, :location_type_id,
:region_id, :updated_by, :website
# set schema name and table name for TakebackDBMS
self.table_name ="recycle.Location"
# define associations
has_many :companyContacts
belongs_to :location_type
belongs_to :company
belongs_to :address
belongs_to :region
default_scope order: 'location_name' # return locations list in Alphabetical order
accepts_nested_attributes_for :address, :reject_if => :all_blank
#validations
validates :location_name, presence: true, length: { maximum: 100 }
validates :created_by, length: { maximum: 50 }
end
Looks like one of your gems/plugins already defines a Location Class.So is the error.
To resolve this,you should be changing your Location class in your app to some name like Location1
class Location1 < ActiveRecord::Base
This should solve your problem.And don't forget to change your Model file name to location1.rb
I recently upgraded an app to rails 3.2.2.
I'm using Factory_girl
Factory.sequence :name do |n| "name-#{n}" end
Factory.define :user do |u| u.first_name{ Factory.next(:name) }
u.last_name { |u| 'last_' + u.first_name } u.password 'secret'
u.password_confirmation { |u| u.password } u.sequence(:email) { |i|
"user_#{i}#example.com" }
end
and this simple test
specify { Factory.build(:user).should be_valid }
generate the following warning
DEPRECATION WARNING: You're trying to create an attribute user_id'.
Writing arbitrary attributes on a model is deprecated. Please just use
attr_writer` etc. (called from block (2 levels) in
at...
How can I get rid of it?
It's probably because you haven't prepared/migrated your test database with updated column definitions, thus it thinks you're trying to arbitrarily set the attribute.
Run rake db:test:prepare to make sure it's updated.
Here's the source code of that method, where you can see Rails checks for the column or attribute first, then warns if they're not found.
I've met the same warning with the following code:
Ad model:
class Ad < ActiveRecord::Base
belongs_to :user
end
Factories:
FactoryGirl.define do
factory :ad do
association :user
end
end
FactoryGirl.define do
factory :user do
first_name {Factory.next(:first_name)}
last_name {Factory.next(:last_name)}
email {|x| "#{x.first_name}.#{x.last_name}#{Factory.next(:count)}#test.com"}
password Forgery(:basic).password
confirmed_at Date.today << 10
end
end
Test
require 'spec_helper'
describe Ad do
before(:each) do
#ad = Factory.build(:ad)
end
"it is not valid without a user"
end
Running the test gave me a similar error.
Adding
attr_accessor :user
to the Ad model fixed the warning.
I hope it helps.
I had this same warning while doing tests in Rspec and my issue was that I had a Parent model and Child model where I accidentally had this:
class Child < ActiveRecord::Base
belongs_to :parent
end
......
class Parent < ActiveRecord::Base
belongs_to :child
end
Unknown validator: 'email_format'
Rails.root: /home/saran/work_space/rails_apps/test_app
Application Trace | Framework Trace | Full Trace
app/models/user.rb:2
app/controllers/user_controller.rb:5:in `create'
my user model file as below:-
class User < ActiveRecord::Base
validates :email, :presence => true, :uniqueness => true, :email_format => true
end
my lib class introduced as below:
:~/work_space/rails_apps/test_app/lib$ cat email_format_validator.rb
class EmailFormatValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
unless value =~ /^([^#\s]+)#((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
object.errors[attribute] << (options[:message] || "is not formatted properly")
end
end
end
I'm using Rails version 3.0
I had the same problem.
To solve it, I created a new folder "validators" in "config/lib".
Then I added this to config/application.rb:
config.autoload_paths += %W(#{config.root}/lib/validators/)
Modify the User Model like below:
class User < ActiveRecord::Base
require "email_format_validator"
validates :email, :presence => true, :uniqueness => true, :email_format => true
end