Rails uninitialized constant name error - ruby-on-rails

I keep getting this error:
NameError (uninitialized constant Character::Messagemissife):
uninitialized constant Mime::HTML
The error is coming from this line:
if #character.messagemissives
character.rb
has_many :messagemissives, dependent: :destroy
messagemissive.rb
class Messagemissive < Missive
self.table_name = 'messagemissives'
belongs_to :character
end
missive.rb
class Missive < ActiveRecord::Base
self.abstract_class = true
end
I have a class Messagemissive, but not Messagemissife. Of course, it looks like a typo error. But I can't find "Messagemissife" anywhere in any of my files. I've used the Find function in Sublime Text 2, I've used the mac Finder search, I've cleared the cache, I've restarted the server several times, I've restarted the computer several times. Still this error won't go away. What am I doing wrong?

You are seeing this behaviour because of rails's default naming convention. When you call #character.messagemissives, rails is actually looking for a model with it's corresponding singular term Messagemissife and not Messagemissive. You can confirm this by typing"Messagemissives".singularize
in rails console which will return you "Messagemissife".
To fix this issue, either you can mention the class name with association like
has_many :messagemissives, class_name: 'Messagemissive'
or as mentioned here, in /config/initializers/inflections.rb, just add
ActiveSupport::Inflector.inflections do |inflect|
inflect.irregular 'messagemissive', 'messagemissives'
end
Hope this will help.

Related

Uninitialized constant Ahoy::QueryMethods - Ahoy Gem

I'm using the Ahoy Gem (https://github.com/ankane/ahoy) to track visits and events. When I try to use their where_event method to query the event model as described in the docs I get this error:
[191] pry(main)> Ahoy::Event.where_event("Reach", business_id: 4072).count
NameError: uninitialized constant Ahoy::QueryMethods
from /Users/rfrisch/projects/impact/app/models/ahoy/event.rb:2:in `<class:Event>'
event.rb
class Ahoy::Event < ActiveRecord::Base
include Ahoy::QueryMethods
self.table_name = "ahoy_events"
belongs_to :visit
belongs_to :user
end
As Ahoy::QueryMethods is provided by the gem I'm not sure how to go about addressing this error.
If I comment out the include line on event.rb then I can properly record events in the table but then I lose the ability to use the where_event method.
Any help getting this to work would be appreciated.
Turns out I need to actually restart the console vs. just running reload!. Now all works as expected.

Manually adding data to a namespaced model in rails

I'm trying to manually add data to a table in rails using the rails console, but I keep getting a undefined local variable or method error.
The model is namespaced under ratings:
models/ratings/value_for_money_score.rb
class Ratings::ValueForMoneyScore < ApplicationRecord
end
To try and manually add a record to the database, I run the following in the console:
$ RatingsValueForMoneyScore.create(score: '1', description:"Terrible, definitely not worth what was paid!")
And I get this error: NameError: uninitialized constant RatingsValueForMoneyScore
I have tried a few different versions such as
RatingsValueForMoneyScores.create,
Ratings_ValueForMoneyScores.create,
ratings_value_for_money_scores.create but keep getting the same error. What am I doing wrong?
Try
::ValueForMoneyScore.create(score: '1', description:"Terrible, definitely not worth what was paid!")
The error is descriptive enough in this case, the class RatingsValueForMoneyScore pretty much doesn't exist. Check your namespace, you have a class name (which should be singular) Rating, and the module ValueForMoneyScore. You'd use either
(after renaming the class to Rating)
Rating.create(...)
or
ValueForMoneyScores.create(...)
Your syntax is equivalent to:
class Rating
module ValueForMoneyScores < ApplicationRecord
...
end
end
The answer was a combination of input, so collecting that in one answer.
My namespaces weren't properly set up (I was using "Ratings" rather than "Rating"), so I fixed this for the tables. My models then looked as follows:
models/rating.rb
class Rating < ApplicationRecord
end
models/rating/value_for_money_score.rb
class Rating::ValueForMoneyScore < ApplicationRecord
end
And then this command worked for creating records in the rating_value_for_money_score table
$ Rating::ValueForMoneyScore.create(score: '1', description: "Test")

Processing ActiveRecord::Reflections -- some model reflections coming up empty (Rails 4.2)

Rails & ActiveRecord 4.2.1, Ruby 2.2.0
EDIT: Please note this question is mostly looking for a discussion of how the Reflections aspect of ActiveRecord works in order to better understand AR and Rails.
I am working on a Concern that looks into an ActiveRecord model's associations and creates callbacks based on those associations. Tests on individual files or examples pass. However, when testing the full suite or running the dev server, it fails because certain models return nil for reflections. The gist:
module CustomActivityMaker
extend ActiveSupport::Concern
module ClassMethods
# #param {Array[Symbols]} assns
# 'assns' params is a list of a model's associations
def create_activity_for(assns)
assns.each do |assn|
r = self.reflect_on_association(assn)
if r.is_a?(ActiveRecord::Reflection::ThroughReflection)
# For a through association, we just track the creation of the join table.
# byebug
r.source_reflection.klass # <== source_reflection unexpectedly ends up being nil
else
r.klass
end
...
end
end
end
end
Invoked like so:
# models/contact.rb
class Contact < ActiveRecord::Base
has_many :emails
has_many :addresses
has_many :phone_numbers
has_many :checklists
has_many :checklist_items, through: :checklists
create_activity_for :checklist_items
...
end
# models/checklist.rb
class Checklist < ActiveRecord::Base
belongs_to :contact
has_many :checklist_items
...
end
# models/checklist_item.rb
class ChecklistItem < ActiveRecord::Base
belongs_to :checklist
has_one :matter, through: :checklist
...
end
The error is shown in the comment note in CustomActivityMaker. When using byebug, the variable r is an ActiveRecord::Reflection::ThroughReflection. The call to source_reflection should be an ActiveRecord::Reflection::HasManyReflection, with 'klass' giving me the ChecklistItem class.
However :source_reflection comes up nil. Using byebug to inspect the error, the through class Checklist does not have any reflections:
Checklist.reflections # <== {}
Of course, this is not the result if I make an inspection in the console or when running an individual test.
I'm not understanding the Rails loading process, and how and when it builds ActiveRecord reflections, and when and how I can reliably access them. Any insight?
I couldn't find any resources to guide me through Rails' inner-workings, so instead I went to look at a popular gem that likewise needs to parse through ActiveRecord::Reflections, ActiveModel::Serializer, since it too would likely have to deal with Rails not loading things as it wished. There, I found:
included do
...
extend ActiveSupport::Autoload
autoload :Association
autoload :Reflection
autoload :SingularReflection
autoload :CollectionReflection
autoload :BelongsToReflection
autoload :HasOneReflection
autoload :HasManyReflection
end
Adding this to my concern solved my issues. From the ActiveSupport::Autoload docs: "This module allows you to define autoloads based on Rails conventions (i.e. no need to define the path it is automatically guessed based on the filename) and also define a set of constants that needs to be eager loaded".

has_one unitialized constant when using .build_

I have situation where an assignment has one training session associated with it
class Assignment < ActiveRecord::Base
has_one :trainingsession
end
class TrainingSession < ActiveRecord::Base
belongs_to :assignment
has_many :drills
end
I keep getting a uninitialized constant error when I'm trying to build an object with a has_one relationship
I'm using the following to build the training session in my controller
#activetrainingsession = #assignment.build_trainingsession
And that line blows up with the uninitialized constant
Something that seems like it should be straightforward!!
By convention, Rails uses camelize and underscore to switch between camel case and underscored representations. This means, in your case, that TrainingSession would be properly referenced as training_session (not trainingsession).
You need:
#activetrainingsession = #assignment.build_training_session
But, to follow said convention all the way through, it may be better as:
#active_training_session = #assignment.build_training_session

Issue with custom inflections in Ruby on Rails 3.0.3

I have a model called produccion_alternativa.
I added a new inflection rule in config/initializers/inflections.rb, like this:
inflect.irregular('produccion_alternativa', 'producciones_alternativas')
I have other model called productor that has a relation with produccion_alternativa:
class Productor < ActiveRecord::Base
has_many :producciones_alternativas
class ProduccionAlternativa < ActiveRecord::Base
belongs_to :productor
When I try to get all the producciones_alternativas for a productor, I get this error:
irb(main):010:0> Productor.first.producciones_alternativas
NameError: uninitialized constant Productor::ProduccionesAlternativa
Any ideas?
I see several others having the same problem. Couldn't find an answer why this happens. So in the meantime you could just try this:
has_many :producciones_alternativas, :class_name => "ProduccionAlternativa"
Your Fail is that you pluralized both words in has_many association. You used:
has_many :producciones_alternativas
but based on the class name ProduccionAlternativa the plural is produccion_alternativas because only the last word is pluralized! So this should work:
has_many :produccion_alternativas
To check the Plural of a word type "your_word".pluralize in the rails console!
I found another solution too. I added another rule on inflection.rb:
inflect.irregular('ProduccionAlternativa', 'ProduccionesAlternativas')
inflect.irregular('produccion_alternativa', 'producciones_alternativas')
At least, now it's working as I want.

Resources