I'm getting the error "uninitialized constant Assignment::AssignmentsCourse". Here are my models:
assignment.rb
class Assignment < ActiveRecord::Base
has_many :assignmentsCourses
has_many :courses, :through => :assignmentsCourses
attr_accessible :name, :dateAssigned, :dateDue, :description, :weight, :category_tokens
attr_reader :category_tokens
def category_tokens=(ids)
puts 'el ids: ', ids.split(",")
self.courseIds = ids.split(",")
end
end
course.rb
class Course < ActiveRecord::Base
has_and_belongs_to_many :assignments
end
AssignmentCourse.rb
class AssignmentCourse < ActiveRecord::Base
belongs_to :assignment
belongs_to :course
attr_accessible :assignment_id, :course_id
end
has_many :assignmentsCourses
This and all of your fields should not be camel cased it is not ruby style and it breaks the class loading. The end should only be pluralized too, not both words. Behind the scenes activerecord depluralizes the symbol you provide and does class loading similar to require. If you tried require 'activeRecord' that would not work for example. Ruby uses underscores to derive multi word class names.
It should be:
has_many :assignment_courses
Change the has many though too. Your accessors should not be camel cased either ruby_style_is_to_underscore.
Related
I have a User model that can have an email and a phone number, both of which are models of their own as they both require some form of verification.
So what I'm trying to do is attach Verification::EmailVerification as email_verifications and Verification::PhoneVerification as phone_verifications, which are both STIs of Verification.
class User < ApplicationRecord
has_many :email_verifications, as: :initiator, dependent: :destroy
has_many :phone_verifications, as: :initiator, dependent: :destroy
attr_accessor :email, :phone
def email
#email = email_verifications.last&.email
end
def email=(email)
email_verifications.new(email: email)
#email = email
end
def phone
#phone = phone_verifications.last&.phone
end
def phone=(phone)
phone_verifications.new(phone: phone)
#phone = phone
end
end
class Verification < ApplicationRecord
belongs_to :initiator, polymorphic: true
end
class Verification::EmailVerification < Verification
alias_attribute :email, :information
end
class Verification::PhoneVerification < Verification
alias_attribute :phone, :information
end
However, with the above setup I get the error uninitialized constant User::EmailVerification. I'm unsure of where I'm going wrong.
How I structure this so that I can access email_verifications and phone_verifications on the User model?
When using STI you don't need (or want) polymorphic associations.
Polymorphic associations are a hack around the object-relational impedance mismatch problem used to setup a single association that points to multiple tables. For example:
class Video
has_many :comments, as: :commentable
end
class Post
has_many :comments, as: :commentable
end
class Comment
belongs_to :commentable, polymorphic: true
end
The reason they should be used sparingly is that there is no referential integrity and there are numerous problems related to joining and eager loading records which STI does not have since you have a "real" foreign key column pointing to a single table.
STI in Rails just uses the fact that ActiveRecord reads the type column to see which class to instantiate when loading records which is also used for polymorphic associations. Otherwise it has nothing to do with polymorphism.
When you setup an association to a STI model you just have to create an association to the base inheritance class and rails will handle resolving the types by reading the type column when it loads the associated records:
class User < ApplicationRecord
has_many :verifications
end
class Verification < ApplicationRecord
belongs_to :user
end
module Verifications
class EmailVerification < ::Verification
alias_attribute :email, :information
end
end
module Verifications
class PhoneVerification < ::Verification
alias_attribute :email, :information
end
end
You should also nest your model in modules and not classes. This is partially due to a bug in module lookup that was not resolved until Ruby 2.5 and also due to convention.
If you then want to create more specific associations to the subtypes of Verification you can do it by:
class User < ApplicationRecord
has_many :verifications
has_many :email_verifications, ->{ where(type: 'Verifications::EmailVerification') },
class_name: 'Verifications::EmailVerification'
has_many :phone_verifications, ->{ where(type: 'Verifications::PhoneVerification') },
class_name: 'Verifications::PhoneVerification'
end
If you want to alias the association user and call it initiator you do it by providing the class name option to the belongs_to association and specifying the foreign key in the has_many associations:
class Verification < ApplicationRecord
belongs_to :initiator, class_name: 'User'
end
class User < ApplicationRecord
has_many :verifications, foreign_key: 'initiator_id'
has_many :email_verifications, ->{ where(type: 'Verifications::EmailVerification') },
class_name: 'Verifications::EmailVerification',
foreign_key: 'initiator_id'
has_many :phone_verifications, ->{ where(type: 'Verifications::PhoneVerification') },
class_name: 'Verifications::PhoneVerification',
foreign_key: 'initiator_id'
end
This has nothing to do with polymorphism though.
With Rails 4.1 I can't seem to get my rails associations to work when using modules.
I have Objects within the FG module:
module FG
class Object < ActiveRecord::Base
belongs_to :user
has_one :email
has_one :phone
end
end
And Emails in the global space:
class Email < ActiveRecord::Base
belongs_to :object, class_name: 'FG::Object'
has_many :objects, class_name: 'FG::Object'
end
When I try
email.objects << object
I get the following error:
ActiveModel::MissingAttributeError
can't write unknown attribute `object_id'
Am I missing something in the association setup?
You could write your Email code this way:
class Email < ActiveRecord::Base
has_many :objects, class_name: 'FG::Object', foreign_key: 'email_id'
end
This will only work if you have an email_id in your objects table. You can not use has_many and belongs_to referring to the same class. That would mean you have an object_id in the one table and an email_id in the other.
You could also write:
class Email < ActiveRecord::Base
belongs_to :object, class_name: 'FG::Object', foreign_key: 'object_id'
end
That depends on your database construction.
I was thinking of the relationships in a conflicting way.
In order for the associations to make sense, I needed to organize them in the following way:
module FG
class Object < ActiveRecord::Base
belongs_to :user
belongs_to :email
belongs_to :phone
end
end
class Email < ActiveRecord::Base
has_many :objects, class_name: 'FG::Object'
end
Hi I have three tables like the following:
class Workitem < ActiveRecord::Base
has_many :effort
attr_protected
end
class Effort < ActiveRecord::Base
attr_protected
belongs_to :workitem
belongs_to :person
end
class Person < ActiveRecord::Base
attr_accessible :given_name, :mgrid, :surname, :id
has_many :effort
end
The idea is to keep track of how many days a person has spent on a particular work item through efforts table. Could somebody verify if my relationships are correct? But this doesn't seem to work. Am I missing something here?
Also, I can't understand the has_many :through kind of associations. Can somebody please give me an idea if that is what I'm supposed to use in this case?
You would usually have the child as a plural object:
class Workitem < ActiveRecord::Base
has_many :efforts
attr_protected
end
class Person < ActiveRecord::Base
attr_accessible :given_name, :mgrid, :surname, :id
has_many :efforts
end
And I'd recommend using attr_accessible instead of attr_protected
If a Foo had many Bars and the Bars belonged to many Foos, it might look like this:
class Foo < ActiveRecord::Base
has_many :foo_bar
has_many :bars, through => :foo_bar
end
class Bar < ActiveRecord::Base
has_many :foo_bar
has_many :foos, through => :foo_bar
end
class FooBar
belongs_to :foo
belongs_to :bar
end
Something like that anyway. There's a load of help on Railcasts here
Also, there's a trillion examples on SO.
Hope that helps
I'm currently working on a small project using Ruby On Rails 3.2 to create a database that contains several unique Models. Each Model has many Elements and each Element has the potential to belong to many Models. I have been able to set up the models in the following manner:
class Model < ActiveRecord::Base
has_many :model_elements
has_many :elements, :through => :model_elements
attr_accessible :elements, :name, :notes, :ref
end
class Element < ActiveRecord::Base
has_many :model_elements
has_many :models, :through => :model_elements
attr_accessible :elementType, :name, :notes, :ref
validates_presence_of :name
end
class ModelElement < ActiveRecord::Base
belongs_to :Model
belongs_to :element
attr_accessible :model_id, :created_at, :element_id
end
My question is how do I add multiple Elements to a single Model? I've tried to find some documentation but I can't find anything. Currently I'm trying to do the following:
#model.elements = #element
Where #element is a predefined element however it's throwing the following error:
undefined method `each' for #<Element:0x007ff803066500>
Any help would be greatly appreciated.
Try
#model.elements << #element
collection.create(attributes = {})
Returns a new object of the collection type that has been instantiated with attributes, linked to this object through the join table, and that has already been saved.
#model.elements.create(:name => "example")
Amar's answer is correct. If you wanted you can simplify your models further by using the has_and_belongs_to_many association.
class Model < ActiveRecord::Base
has_and_belongs_to_many :elements, :join_table => :model_elements
end
class Element < ActiveRecord::Base
has_and_belongs_to_many :models, :join_table => :model_elements
end
#model.elements << #element
I'm somewhat confused by my options for custom validations in Rails 3, and i'm hoping that someone can point me in the direction of a resource that can help with my current issue.
I currently have 3 models, vehicle, trim and model_year. They look as follows:
class Vehicle < ActiveRecord::Base
attr_accessible :make_id, :model_id, :trim_id, :model_year_id
belongs_to :trim
belongs_to :model_year
end
class ModelYear < ActiveRecord::Base
attr_accessible :value
has_many :model_year_trims
has_many :trims, :through => :model_year_trims
end
class Trim < ActiveRecord::Base
attr_accessible :value, :model_id
has_many :vehicles
has_many :model_year_trims
has_many :model_years, :through => :model_year_trims
end
My query is this - when I am creating a vehicle, how can I ensure that the model_year that is selected is valid for the trim (and vice versa)?
you can use custom validation method, as described here:
class Vehicle < ActiveRecord::Base
validate :model_year_valid_for_trim
def model_year_valid_for_trim
if #some validation code for model year and trim
errors.add(:model_years, "some error")
end
end
end
You can use the ActiveModel::Validator class like so:
class VehicleValidator < ActiveModel::Validator
def validate(record)
return true if # custom model_year and trip logic
record.errors[:base] << # error message
end
end
class Vehicle < ActiveRecord::Base
attr_accessible :make_id, :model_id, :trim_id, :model_year_id
belongs_to :trim
belongs_to :model_year
include ActiveModel::Validations
validates_with VehicleValidator
end