Rails: Is this a use case for Single Table Inheritance (STI)? - sql

Consider this setup. Please understand that our setup is much more detailed but this is a simple example.
competition which has name. This is an annual competition.
competition_instances which has location, starts_at.
Each competition has sports which has name.
Example:
competition.name: "Super Bowl" has different competition_instances every year but sport remains the same.
Conversely, competition.name: "Olympics" has different competition_instances and different sports in each competition_instance.
Would it be best to create competition_sports and competition_instance_sports with competition_instance_sports as a subclass of competition_sports?
GOAL: Use competition_instance_sports records if they exist, otherwise use the competition_sports record. In our real world app, each competition/competition_instance can have 20-50 sport records. How can we best achieve?

Based on what I understand from the question I cannot see where STI will be helpful in this situation. However a join table will get you where you want.
I suggest creating a new table sports, this model will have all the specific details of each sport. The competition_instance.rb will have one/many sport.rb. competiton.rb will have many sports through competition_instance.rb.
competition.rb
Class Competition < ActiveRecord::Base
has_many :competition_instances
has_many :sports, through: :competition_instances
end
competition_instance.rb
Class CompetitionInstance < ActiveRecord::Base
belongs_to :competition
belongs_to :sport
end
sport.rb
Class Sport < ActiveRecord::Base
has_many :competition_instances
end
By using this design you will be able to achieve the following:
1- You will have your predefined sports in your database along with their specific properties.
2- Each competition will have .sports which will give all the sports in this competition for the olympics case.
3- You will be able to set specific properties for each competition instance (example event_start_time and event_end_time) in the competition instance table.

I'm just thinking of the case where there are standard sports which are always in the Olympics and some which are added on, such as those proposed by the host country.
I would use Polymorphic Associations, in a "reverse manner".
class Competition < ActiveRecord::Base
has_many :competition_instances
has_many :competition_sports, as: :event
end
class CompetitionInstance < ActiveRecord::Base
belongs_to :competition
has_many :competition_sports, as: :event
def events_array # neater by sacrificing ActiveRecord methods
competition.competition_sports + competition_sports
end
def events # messier, returns ActiveRecord relationship
CompetitionSport.where( " ( event_id = ? AND event_type = 'Competition' ) OR
( event_id = ? AND event_type = 'CompetitionInstance')", competition_id, id )
end
end
class Sport < ActiveRecord::Base
has_many :events, as: :competition_sport
end
class CompetitionSport < ActiveRecord::Base
belongs_to :sport
belongs_to :event, polymorphic: true
end
This allows:
competition.competition_sports # standard sports
competition_instance.competition_sports # only those specific for this instance
competition_instance.events # includes sports from both

Aiming at the original question of "Is this a use case for STI", it will be difficult to say if this is or not without seeing the full complexity of your environment. But here's are some things to consider:
Abridged from How (and When) to Use Single Table Inheritance in Rails - eugenius blog:
STI should be considered when dealing with model classes that share much of the same functionality and data fields, but you want more granular control over extending or adding to each class individually. Rather than duplicate code or forego the individual functionalities, STI permits you to use keep your data in a single table while writing specialized functionality.
You've simplified your example, but it sounds like competition and competition_instance are NOT essentially the same object, with minor behavioral differences. With what you've described, I would probably rename these objects to event and competition, or whatever makes better sense to you in terms of illustrating what these objects are actually representing. I think of 'The Olympics' as a generic event, and '100m Dash' as a competition taking place at The Olympics. Or "The SuperBowl" only hosted one competition in 2014, "SuperBowl XLIX".
You've also tagged this question with database-normalization, which STI won't help. If the attributes differ slightly between your shared objects you'll end up with null fields everywhere.
I refer you to the other answers here to see how you should probably set those objects up to behave as desired.

This is not a case for single table inheritance, because competition_instance is not a substitute for competition and 1 competition can have many competition_instances. So you have 3 tables:
competitions
sports
competition_instances
competition_instances has a foreign key to competitions because 1 competition can have many competition_instances but each competition_instance has exactly one competition.
Whether you attach sports to competitions or competition_instances depends on the specific constraints of your use case. I don't exactly know what you mean by "each competition/competition_instance can have 20-50 sport records". I would expect each competition_instance to have exactly one sport, so you might leave it at that, or you might attach a collection of sports to a competition as well, so that you can retrieve new competitions by sport before there is a competition_instance. I'd need more details on your use case to give you further advice.

Related

Ruby on Rails - has_many relationship with condition that needs a join

I'm working in RoR 3..2.11. I have 4 classes: Person, Agreement, Relationship, and Role. My situation is as follows:
This is in Person:
has_many :relationships
has_many :agreements, {
through: :relationships
}
has_many :current_agreements, {
source: :agreements,
through: :relationships,
conditions: "agreements.start_date <= NOW() AND agreements.end_date >= NOW()"
}
This is in Relationship:
belongs_to Role
A new role has been added to the database ("Past"), so that live agreements can be assigned to another person. Sot the previous person on the agreement still has a relationship to the agreement, but should no longer have it come up under current_agreements. So I need to take into account relationships.role.name. Something like this:
has_many :current_agreements, {
source: :agreements,
through: :relationships,
conditions: "agreements.start_date <= NOW() AND agreements.end_date >= NOW() AND role.name != 'Past'"
}
The issue here is pretty clear cut, role is not in the query so role.name fails. Is there a way to join the role table by the relationships.id for the association?
I've thought of redefining current_agreements as a method instead, but the project needs it to be an association in certain places so I'd really rather just redefine the association instead of re-factoring the whole thing.
I think that current_agreements shouldn't be an association. Does it make sense to ever say
#person.current_agreements << #agreement
? If so, would this set start date and end date, and the associated role?
You say you don't want to refactor it but you could spend more time trying to bash a square peg into a round hole by keeping it as an association.
What about a named scope on Agreement like
#in Agreement
scope :current, includes(:role).where("agreements.start_date <= NOW() AND agreements.end_date >= NOW() AND role.name != 'Past'")
Then you can say
#person.agreements.current
I think that Max Williams is right. This should not be a relation, and I like the Max's approach.
But something that sounds complicated, it's that you don't want to refactor. Remember that one important thing when you design software is to be prepared for the change. If it's difficult to refactor, maybe you should take a look to your tests, or the way that your classes are coupled.
Take a look to the Max's approach, it's simple and clear. And with Ruby/Rails (and of course with tests) the refactor could be enjoyable, to get your desirable behavior.
I like this book. It could explain better than me, my previous words.

Association between one model and an attribute of another

I'm trying to create an association for a beta meat-sale application between one model, Cuts, and the "animal_type" attribute of another model, Animal, such that I could list all the cuts associated with a particular animal_type (or associated with an animal that has that type as an attribute).
In other words, if animal_type is "cow", I should be able to call up a list of all the cuts (ribeye, tenderloin, etc) associated with cows. I'm new to Rails, and this is fairly above my head.
My idea was to create an animal_type column in Cuts and Animals, to associate each cut with a type of animal, so I could do something along the lines of
#cuts = Cut.where(:animal_type => Animal::animal_type[:Cow])
No idea if that works, though, and what else I need to do to make this association possible. Can anybody help point me towards a way of thinking this through? Or does anyone have any good resources I could look at to help me with this specific problem? I've been looking through Rails Guides, and they're helpful, but they don't really give me a way to answer this.
You could have a Cuts model and an Animal model. Cuts could have a string attribute called "name" which would store the cut type such as ribeye, tenderloin etc. Animal could have a string attribute called animal_type. You could then setup a has_many association between Animals and Cuts. Something like this:
class Animal < ActiveRecord::Base
attr_accessible :animal_type
has_many :cuts
end
class Cuts < ActiveRecord::Base
attr_accessible :name
belongs_to :animals
end
This should be a good start

Best way to add a second parameter to route

I want my route to be something like cars(/:country/):car_id, what is the best way to do that? Only "cars" will list all the cars and "cars /: country" will list all the cars that are made in that country.
Now I have my route like this resources: cars,: path => "cars (/:country)" and I check in cars#index action if params[:country] is nil to determine what will be retrieved from the database .
My solution feels wrong and ugly and I guess the best solution and cleanest would be to make a country model, but do not really know how to organize it all up, tips?
country must have a slug and so do car_id too (using friendly_id for car_id). It feels like I should have a car table with name and slug thats all i have figured out.
Thanks!
First I'd say that your current solution is NOT ugly, nor wrong, at worst it's pedestrian. But without seeing all the involved models and associations, I can only give a general answer.
First, A country model, probably a good idea, but how do you relate it to the cars model?
You could do this:
class Country << ActiveRecord::Base
has_may :cars
end
class Car << ActiveRecord::Base
belongs_to :country
end
That would support semantics where by you could select a country, and get all cars belonging to a certain country, i.e.
#cars = Country.find('USA').cars
OR, you could do something like:
class Car << ActiveRecord::Base
has_one :country
end
class Country << ActiveRecord::Base
end
That would enable a different semantic:
#country = Car.find('Jeep').country
The point is to think of the query semantics you'd like to have in your app, and then define your associations to support the semantics that make sense for your app. I've posted very simple associations, you may end up with multiple and more complex associations, just depends on how you need to query the database and the associated models.
UPDATE
You posted:
I want my route to be something like cars(/:country/):car_id,
That doesn't make sense, if you know the specific car_id, you don't need any filtering or extra searching.
Sound like you want these URLs:
/cars # all cars
/cars/:country # all cars in country
/car/:id # a specific car
The first and third routes are probably there assuming you've defined the full set of RESTful routes for cars, i.e.
config/routes.rb
resources :cars
You just need to add to routes.rb:
GET '/cars/:country' => 'cars#index'
Then in app/controllers/cars_controller.rb:
def index
if params[:country]
#cars = Car.where("country_id = ?", params[:country])
else
#cars = Car.all
end
end
This assumes you have a relationship set up whereby each car record has a country_id attribute. That can come about in several ways, for example:
class Car < ActiveRecord::Base
belongs_to :country
end
That says my car table has a country_id attribute, and I can do something like:
#car = Car.find(1001)
"The car is in #{#car.country.name}"

Has_many :through association

I made a relationship with the three models using has_many :through:
class Curriculum class < ActiveRecord::Base
has_many :interests
has_many :vacancies,: through => :interests
end
class Vacancy class < ActiveRecord::Base
has_many :interests
has_many :resumes,: through => :interests
end
class Interest < ActiveRecord:: Base
belongs_to :vacancy
belongs_to :curriculum
end
And to create curriculum and vacancy, I create them by administrative, i need to know how can i create the interest to the id of the vacancy, and how it will be logged on the system I have to get the id of it and make the relationship in creating a new bank interest. I wonder how I can program it to do so, and I wonder how the controller will get the create action, and what better way to do this.
First, try to read the whole "Guide to Rails on Associations", especially the part about has_many :through. Then check your schema if your db is migrated and contains for the table interests the necessary foreign keys to curriculums and vacancies called curriculum_id and vacancy_id.
If that is all in place, the following code will create the relationship between two objects:
#curr = Curriculum.find(1)
#vac = Vacancy.find(1)
#curr.interests << #vac
#curr.save
The last two lines creates an interest between #curr and #vac and store that on the database. So you should not use IDs and handle them directly, but work with objects instead.
The second part now is to provide a UI to allow the definition (and removal) of interests between curricula and vacancies. The base flow here is:
You have one curriculum in focus.
You have a link to add / remove curricula.
The view that opens shows a list of possible vacancies, where every vacancy has a checkbox.
By selecting (or deselecting) the check boxes, the IDs of the vacancies will be held in the params of the request sent to the controller.
See the (older) podcast Railscast #52 how to do that in a similar context. Or see the example for has_many :through with checkboxes.
An alternative way would be to use JQuery autocomplete, and add so interests one-by-one. See the nice podcast Railscast #258 which uses JQuery Tokeninput for that.
I think this is what your looking for:
HABTM Checkboxes
That's the best way to use an Has and Belongs to many association.

Help with Rails find_by queries

Say if #news_writers is an array of records. I then want to use #news_writers to find all news items that are written by all the news writers contained in #news_writers.
So I want something like this (but this is syntactically incorrect):
#news = News.find_all_by_role_id(#news_writers.id)
Note that
class Role < ActiveRecord::Base
has_many :news
end
and
class News < ActiveRecord::Base
belongs_to :role
end
Like ennen, I'm unsure what relationships your models are supposed to have. But in general, you can find all models with a column value from a given set like this:
News.all(:conditions => {:role_id => #news_writers.map(&:id)})
This will create a SQL query with a where condition like:
WHERE role_id IN (1, 10, 13, ...)
where the integers are the ids of the #news_writers.
I'm not sure if I understand you - #news_writers is a collection of Role models? If that assumption is correct, your association appears to be backwards - if these represent authors of news items, shouldn't News belong_to Role (being the author)?
At any rate, I would assume the most direct approach would be to use an iterator over #news_writers, calling on the association for each news_writer (like news_writer.news) in turn and pushing it into a separate variable.
Edit: Daniel Lucraft's suggestion is a much more elegant solution than the above.