Rails 3 superclass mismatch for class Location - ruby-on-rails-3

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

Related

Rails 5 - Mongoid - Concerns

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.

Nested json jbuilder for photo feed having n+1 major issues

I am having performance issues on one of my api views so I ran the Bullet gem and found some major N+1 issues with the view.
The api is being consumed so the format has to remain identical.
Bullet N+1 output:
localhost:3000/api/v1/games/1/game_feed N+1 Query detected
CompletedQuest => [:comments] Add to your finder: :include =>
[:comments] N+1 Query method call stack
/app/views/api/v1/games/game_feed.json.jbuilder:3:in block in
_b3b681b668d1c2a5691a5b3f7c15bb8e' /app/views/api/v1/games/game_feed.json.jbuilder:1:in
_b3b681b668d1c2a5691a5b3f7c15bb8e'
But I don't know how to accomplish the fix. Here are the relevant parts.
View:
json.game_feed(#game_photos) do |f|
json.extract! f, :id, :user_id, :username, :image_url_original, :comments_count, :likes_count
json.comments f.comments do |comment|
json.(comment, :username, :comment)
end
json.likes f.likes do |like|
json.(like, :id, :user_id, :username)
end
end
Controller:
#game_photos = CompletedQuest.game_photos(#game.id)
Model:
def self.game_photos(game_id)
where("completed_quests.game_id = ?", game_id).order("completed_quests.id DESC").just_photos
end
scope :just_photos, -> { where.not( image_file_name: nil ) }
Model relationships:
# CompletedQuests:
belongs_to :user
has_many :comments, dependent: :destroy
has_many :likes, dependent: :destroy
# Comments:
belongs_to :completed_quest, counter_cache: true
belongs_to :user
So basically for each photo in the feed, it then grabs every comment & likes for ever record - obviously this is bad and I see why, but I can't figure out how to fix it with my current structure.
Any help would be appreciated - but one thing is the structure of the JSON must remain identical.
You could include the associated comments in the query as follows:
# app/models/completed_quest.rb
def self.game_photos(game_id)
includes(:comments).where("completed_quests.game_id = ?", game_id).order("completed_quests.id DESC").just_photos
end
This will include all the associated comments in the result, so when you do f.comments in your view, there won't be a database query for comments of each f instance.

Writing arbitrary attributes on a model is deprecated. (Multiple belongs_to on model)

I have multiple belongs_to relationships to the same model. Modeling messages between two users as follows (in the Message model):
belongs_to :to, :class_name => 'User', :foreign_key => 'to_id'
belongs_to :from, :class_name => 'User', :foreign_key => 'from_id'
attr_accessible :to, :from # ...
The corresponding has_many calls are in the User model. Everything works in the spec and the console as I need it to, with the exception of the following deprecation warning (for both from_id and to_id):
DEPRECATION WARNING: You're trying to create an attribute `from_id'. Writing arbitrary attributes on a model is deprecated. Please just use `attr_writer`
The relevant spec follows:
it "can associate users" do
User.delete(:all)
ufrom = FactoryGirl.create(:DrKevorkian)
ufrom.save!
uto = FactoryGirl.create(:JohnSmith)
uto.save!
m = Message.new
m.from = ufrom # <-- Warning here
m.to = uto # <-- Warning here
m.save
m.from.id.should == ufrom.id
m.to.id.should == uto.id
end
It seems to me the warning is happening as a result of the belongs_to association -- is there a cleaner/better way to do this?
Thanks very much.
My experience is that you get this warning if you forgot to run rake db:migrate and rake db:test:prepare after changing your schema.

Can't mass-assign protected attributes for nested form using cocoon and simple_forms in Rails 3 App

The Problem:
I am getting an error message when submitting my form that says:
ActiveModel::MassAssignmentSecurity::Error in AdmissionRecordsController#create
Can't mass-assign protected attributes: admission_record
My Setup:
I am using Rails 3.2.3, with extra gems including Cocoon 1.0.14 and Simple_Form 2.0.2
The View:
My app/views/admission_records/_form.html.haml looks like:
= simple_form_for [#admission, #record] do |f|
= f.simple_fields_for :vital_signs, #record.vital_signs.build do |vs|
= render :partial => "vital_sign_fields", :locals => { :f => vs }
= link_to_add_association "Add Vital Signs", f, :vital_signs
= f.submit
And my app/views/admission_records/_vital_sign_fields.html.haml looks like:
.nested-fields
= f.label :sbp
= f.text_field :sbp
...
= link_to_remove_association "Remove Vital Sign"
What I am basically trying to do is that I have a resource called AdmissionRecord nested within another resource called PatientAdmission (route.rb shown below). I have another resource called VitalSign which I want to be able to create via a nested form (using cocoon and simple_form) when creating the AdmissionRecord
My config/routes.rb file looks like:
resources :patient_admissions do
resources :admission_records
end
The Models:
My app/models/patient_admission.rb looks like:
class PatientAdmission < ActiveRecord::Base
has_many :admission_records, :dependent => :destroy
end
My app/models/admission_record.rb looks like:
class AdmissionRecord < ActiveRecord::Base
belongs_to :patient_admission
has_many :vital_signs, :dependent => :destroy
accepts_nested_attributes_for :vital_signs, :rejects_if => :all_blank, :allow_destroy => true
attr_accessible :vital_signs_attributes
end
And my app/models/vital_sign.rb looks like:
class VitalSign < ActiveRecord::Base
belongs_to :admission_record
attr_accessible # just fields that appear in the form
end
The Controller:
The new and create methods in my AdmissionRecordsController looks like:
before_filter do
#admission = PatientAdmission.find(params[:patient_admission_id])
end
def new
#record = #admission.admission_records.build
end
def create
#record = #admission.admission_records.build(params[:admission_record])
#vital_sign = #record.vital_signs.build(params[:vital_signs])
#vital_sign.save
if #record.save
# Flash success and redirect to the right place
else
# Flash error and render :new
end
end
The Plea:
Please help me find where I'm going wrong. I've googled for hours and have looked at other examples and source code for demo apps such as those found in cocoon_simple_form_demo, but still can't seem to fix this error. If there's any other piece of information needed to debug this problem, please let me know. Thanks!
Okay I just had this problem and fixed it by entering one line of code in the belongs_to model.
# patient_admission.rb
Class PatientAdmission < ActiveRecord::Base
attr_accessible :admission_record_attributes
accepts_nested_attributes_for :admission_record
...
end
Here is another solution to it :)

How do i create an object if it has more than one belongs_to?

I have the following:
class Org < ActiveRecord::Base
has_many :users
has_many :entries
end
class Entry < ActiveRecord::Base
belongs_to :org
belongs_to :user
validates_presence_of :entry_text
end
class User < ActiveRecord::Base
belongs_to :org
has_many :entries
validates_uniqueness_of :user_name
validates_presence_of :user_name, :length => { :minimum => 3 }
end
I can Create Orgs and Users... How do i create an entry if there are two belongs_to? and what is this pattern called?
Double nested resources are tricky. The trick with users usually is to keep it out of your desired entry path.
Your question is kind of broad, but if you specify more information, people would be able to help you better. Also, I would recommend using the gem Devise for your user management system. Since you're using 'users' I would assume you want users from orgs to create entries. The entry created would be a part of org and the user would be the session's current user. Sorry if I am wrong to assume this.
Your routes.rb file can look something like this (assuming rails 3):
resources :orgs do
resources :entries
end
Then the create of your entry controller would look like:
#entry = #org.entries.new(params[:topic])
#entry.user = current_user #or however you are managing the current user's session.
And you'd want to set the org for the entire class by making a method that loads your current org and do a before_filter :loadOrg
def loadOrg
#org = Org.find(params[:id])
end
This is of course assuming your path is something like: /org/(id)/entry/(entry_id)
and not
/org/(id)/user/(user_id)/entry/(entry_id)
which in my opinion is unnecessary and can lead to more problems. You can always create a userpage model that calls all entries by users, but the default route doesn't necessarily have to include users in the path.
I don't see any problem.
#entry = Entry.create(:entry_text => "Hello World!")
Now questions to clarify what do you need:
Can #entry belongs both org and user at the same time? Or it can belongs to only one of them?
Should #entry belongs to at least one of them?
If #entry supposed to belong only one of them, so you should use Polymorphism
http://railscasts.com/episodes/154-polymorphic-association
class Entry < ActiveRecord::Base
belongs_to :textable, :polymorphic => true
validates_presence_of :entry_text
end
class Org < ActiveRecord::Base
has_many :users
has_many :entries, :as => :textable
end
class User < ActiveRecord::Base
belongs_to :org
has_many :entries, :as => :textable
validates_uniqueness_of :user_name
validates_presence_of :user_name, :length => { :minimum => 3 }
end