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

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.

Related

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

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.

What is the best approach to save multiple temperature-curves (which are measured at the same time) in a Database using Rails and SQL

what is the best approach to save multiple temperature-curves by using Ruby On Rails and a SQL-database. The temperature curves are are measured at the same time. And the time for each measured value musst be stored in seconds.
This picute show my problem in an UML. But the assoziation between timeline and curve-measurment isn't correct. Each timeline-value can have several curve-measurments but not in the same curve. In the same curve alle timeline-values must be unique.
In this solution all timeline-values can have several curve-measurments. This ist correct but in this picutre a timeline-value can have several curve-mesaurments in the same curve and that is wrong.
I hope you understand my problem and you can give me some hint to a better approach.
It looks like your CurveMeasurement should be a join between Curve and Timeline:
class Curve < ActiveRecord::Base
has_many :curve_measurements
...
end
class Timeline < ActiveRecord::Base
has_many :curve_measurements
...
end
class CurveMeasurement < ActiveRecord::Base
belongs_to :curve
belongs_to :timeline
validates :curve_id, uniqueness: { scope: :timeline_id }
validates :timeline_id, uniqueness: { scope: :curve_id }
...
end
The important parts for your requirements are the uniqueness scopes in the CurveMeasurement model - this ensures that you can't have more than one measurement for a given curve at a given timeline point.
It would also be possible to do this without the timeline value being a separate model:
class Curve < ActiveRecord::Base
has_many :curve_measurements
...
end
class CurveMeasurement < ActiveRecord::Base
belongs_to :curve
validates :timeline_value, uniqueness: { scope: :curve_id }
...
end
If you wanted to enforce a discrete set of timeline_values, you can use further validations: either numericality or inclusion (see http://guides.rubyonrails.org/active_record_validations.html )
If I understand correctly, a measurement for a given curve is a value, measured at a specific time. And you want to be able to find all values, for all curves, at any given time.
At the same you want to be able to constrain there is only measurement per time, per curve. You can specifically do that in your second model as well.
In your model, your curve_measurements would look like
t.curve_id
t.timeline_id
t.value
You can then specify a constraint (depends on your database, that the combination curve_id, timeline_id has to be ok.
One wonders, if Timeline offers nothing more than just the time in seconds, why not drop that level of indirection?
Granted, if you have Timeline you can just write timeline.curve_measurements, but if you drop the necessity of the timelines table, and just add the time (or timeline) value directly to the curve_measurements table, your table would look something like
t.curve_id :integer, references: curves
t.measured_at :time
t.value
and then to get all measurements at a certain time, just write CurveMeasurement.where(:measured_at => ....)
Which is easier to query (one join less). Also to make sure there is only measurement per curve, per time, you just have to add the similar constraint, specifying that the curve_id, measured_at combination has to be unique.

Is there a better way to structure these database tables?

I'm struggling with the best way to design/query my db on a new Rails app. This is what I have in place right now:
documents:
title
has_many :document_sections
document_sections:
belongs_to :document
habtm :resources
resources_document_sections:
belongs_to :resource
belongs_to :document_section
resources:
text
So it's easy to say document_section.resources. But document.resources is giving me trouble
The only way I've found to do it so far is to collect the document section ids, and then run a second query:
d = Document.last
s_ids = d.document_section_ids
Resource.joins(:document_sections)
.where(document_sections: { id: s_ids })
.uniq
So this starts bad, and gets worse as the queries get more complicated. It's becoming quite a headache every time I have to touch this relationship.
I'm wondering if there is a different pattern that I could follow in laying out these tables, such that querying against them is not such a headache? Or is there a better querying strategy that I'm missing?
Your document has no relationships. You need to add something to both models in a relationship, you can't just add it to document_sections and expect documents to have any kind of relationship to anything.
You need to add a has_many ... through: to your Document:
class Document < ActiveRecord::Base
has_many :document_sections
has_many :relationships, through: :document_sections
end

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.