convert "has many, through" association to simply a "belongs to" association - ruby-on-rails

I wrote a rails program for a non-profit to help track encounters. Originally the thought was that a single encounter might deliver multiple services, hence the setup:
class Encounter < ApplicationRecord
has_many :encounters_services, dependent: :destroy, inverse_of: :encounter
has_many :services, through: :encounters_services
accepts_nested_attributes_for :encounters_services
class Service < ApplicationRecord
has_many :encounters, :through => :encounters_services
has_many :encounters_services, dependent: :destroy, inverse_of: :service
The end user has now figured out that they only want to associate a single service with an encounter. But there's already a lot of data in the database under the original structure. Is there a clean way to convert it to a scenario where a Service "has many" Encounters, and an Encounter "belongs to" a Service, without messing up the data that's already stored in the database in the "EncounterServices" table?
Thanks! I'm still a newbie so I appreciate the help!

I guess you could add a new migration to add a new column to the services and add a little script to set the value from EncountersServices.
Something like
def change
add_column :services, :encounter_id, :integer, index: true
Service.each do |s|
s.update_column :encounter_id, s.encounters.first.id
end
end
You can leave the previous data untouched. Since the old association's data has it's own table, your models' tables won't have garbage.
EDIT: I understood the relationship the wrong way, if an encounter should belong yo a service, the migration would look like this:
def change
add_column :encounters, :service_id, :integer, index: true
Encounter.each do |e|
e.update_column :service_id, e.services.first.id
end
end

Related

Rails: Validating an array of ids

Application
I am working on a college admissions system where a student can make an application to up to 5 courses. The way I have designed this is to have an Application model and a CourseApplication model. An application can consist of many course_applications:
class Application < ActiveRecord::Base
# Assosciations
belongs_to :user
has_many :course_applications, dependent: :destroy
has_many :courses, through: :course_applications
has_one :reference
# Validations
validates :course_applications, presence: true
end
Course Application
class CourseApplication < ActiveRecord::Base
# Intersection entity between course and application.
# Represents an application to a particular course, has an optional offer
# Associations
belongs_to :application
belongs_to :course
has_one :offer, dependent: :destroy
end
I want to make sure that a student cannot apply to the same course twice. I have already done some research but have had no success. This is the UI for a student making an application:
Screenshot of application form
When a course is selected, the course id is added to an array of course ids:
def application_params
params.require(:application).permit(:user, course_ids: [])
end
Right now a student can select the same course twice, I want to prevent them from doing this. Any help is much appreciated.
For the rails side, I would do on the CourseApplication
validates :course, uniqueness: { scope: :application }
For your reference this can be found at: http://guides.rubyonrails.org/active_record_validations.html#uniqueness
Also suggest on the database side to make a migration
add_index :course_applications, [:course, :application], :unique => true
For the validating on the form you will have to write javascript to make sure two things are selected, this will just return an error when someone tries to do it.

Access Active::Record relations from other relations

In rails 4, have a model like:
class User < ActiveRecord::Base
has_many :groups
has_many :contents, through: :groups
has_many :content_masks
has_many(
:hidden_contents,
through: :content_masks,
source: :content,
class_name: "Content"
)
has_many(
:visible_contents,
->{ where("contents.id NOT IN (#{hidden_contents.select('contents.id').to_sql})") },
through: :groups,
class_name: "Content"
)
end
I can't, however, access the hidden_contents relation from the visible_contents relation. Is this possible?
It seems like the relation is called on a specific instance, and I should be able to access it somehow, right?
Would need to see some sample code, but assuming you're trying to do something like User.visible_contents.hidden_contents you're going to get some sort of error. This is because visible_contents returns an AR Relation, which does not contain any of the model-defined relationships (so no, in the strictest sense of answering your question, you can't do this).
You would, however, be able to get away with something like this: User.visibile_contents.first.hidden_contents or User.visible_contents.map(&:hidden_contents). Kind of hard to answer the question accurately without knowing exactly what you're trying to do.

Rails: Address model being used twice, should it be separated into two tables?

I am making an ecommerce site, and I have Purchases which has_one :shipping_address and has_one :billing_address
In the past the way I've implemented this is to structure my models like so:
class Address < ActiveRecord::Base
belongs_to :billed_purchase, class_name: Purchase, foreign_key: "billed_purchase_id"
belongs_to :shipped_purchase, class_name: Purchase, foreign_key: "shipped_purchase_id"
belongs_to :state
end
class Purchase < ActiveRecord::Base
INCOMPLETE = 'Incomplete'
belongs_to :user
has_one :shipping_address, class: Address, foreign_key: "shipped_purchase_id"
has_one :billing_address, class: Address, foreign_key: "billed_purchase_id"
...
end
As you can see, I reuse the Address model and just mask it as something else by using different foreign keys.
This works completely find, but is there a cleaner way to do this? Should I be using concerns? I'm sure the behavior of these two models will always be 100% the same, so I'm not sure if splitting them up into two tables is the way to go. Thanks for your tips.
EDIT The original version of this was wrong. I have corrected it and added a note to the bottom.
You probably shouldn't split it into two models unless you have some other compelling reason to do so. One thing you might consider, though, is making the Address model polymorphic. Like this:
First: Remove the specific foreign keys from addresses and add polymorphic type and id columns in a migration:
remove_column :addresses, :shipping_purchase_id
remove_column :addresses, :billing_purchase_id
add_column :addresses, :addressable_type, :string
add_column :addresses, :addressable_id, :integer
add_column :addresses, :address_type, :string
add_index :addresses, [:addressable_type, :addressable_id]
add_index :addresses, :address_type
Second: Remove the associations from the Address model and add a polymorphic association instead:
class Address < ActiveRecord::Base
belongs_to :addressable, polymorphic: true
...
end
Third: Define associations to it from the Purchase model:
class Purchase < ActiveRecord::Base
has_one :billing_address, -> { where(address_type: "billing") }, as: :addressable, class_name: "Address"
has_one :shipping_address, -> { where(address_type: "shipping") }, as: :addressable, class_name: "Address"
end
Now you can work with them like this:
p = Purchase.new
p.build_billing_address(city: "Phoenix", state: "AZ")
p.build_shipping_address(city: "Indianapolis", state: "IN")
p.save!
...
p = Purchase.where(...)
p.billing_address
p.shipping_address
In your controllers and views this will work just like what you have now except that you access the Purchase for an Address by calling address.addressable instead of address.billed_purchase or address.shipped_purchase.
You can now add additional address joins to Purchase or to any other model just by defining the association with the :as option, so it is very flexible without model changes.
There are some disadvantages to polymorphic associations. Most importantly, you can't eager fetch from the Address side in the above setup:
Address.where(...).includes(:addressable) # <= This will fail with an error
But you can still do it from the Purchase side, which is almost certainly where you'd need it anyway.
You can read up on polymorphic associations here: Active Record Association Guide.
EDIT NOTE: In the original version of this, I neglected to add the address_type discriminator column. This is pernicious because it would seem like it is working, but you'd get the wrong address records back after the fact. When you use polymorphic associations, and you want to associate the model to another model in more than one way, you need a third "discriminator" column to keep track of which one is which. Sorry for the mixup!
In addtion to #gwcoffey 's answer.
Another option would be using Single Table Inhertinace which perhaps suits more for that case, because every address has a mostly similar format.

has_and_belongs_to_many and accepts_nested_attributes_for

class Trip
has_many :trip_places
has_many :places, through: :trip_places
accepts_nested_attributes_for :places
end
class Place
has_many :trip_places
has_many :trips, through: :trip_places
validates :name, uniqueness: true
end
class TripPlace
belongs_to :trip
belongs_to :place
end
So we got a trip which has many places through trip places, and accepts nested attributes for places. Also places must be unique by name.
I'd like to have the following functionality though, and can't find an elegant solution to it:
Let's say we create a trip T, with two places P1 = 'hawaii' and P2 = 'costa rica'
If I edit the trip, and change hawaii to bora bora, it will modify the Place.
The problem is that I'd like to create a new place called bora bora and modify the TripPlace model to update the place_id with the new one.
Same thing goes to destroy, if I destroy a place in the form, I'd like to remove only the reference from the TripPlace, and not the actual Place
And of course, the create functionality should be alike, if the place exists, just create the TripPlace reference.
Right now, I don't think that accepts_nested_attributes_for really helps, but can't think of a good solution for this

Fake a composite primary key? Rails

I have a table with id|patient_id|client_id|active. A record is unique by patient_id, client_id meaning there should only be one enrollment per patient per client. Normally I would make that the primary key, but in rails I have id as my primary key.
What is the best way to enforce this? Validations?
Sounds like you have a model relationship of:
class Client < ActiveRecord::Base
has_many :patients, :through => :enrollments
has_many :enrollments
end
class ClientPatient < ActiveRecord::Base
belongs_to :client
belongs_to :patient
end
class Patient < ActiveRecord::Base
has_many :clients, :through => :enrollments
has_many :enrollments
end
To enforce your constraint I would do it in ActiveRecord, so that you get proper feedback when attempting to save a record that breaks the constraint. I would just modify your ClientPatient model like so:
class Enrollment < ActiveRecord::Base
belongs_to :client
belongs_to :patient
validates_uniqueness_of :patient_id, :scope => :client_id
end
Be careful though because, while this is great for small-scale applications it is still prone to possible race conditions as described here: http://apidock.com/rails/v3.0.5/ActiveRecord/Validations/ClassMethods/validates_uniqueness_of under "Concurrency and Integrity"
As they describe there, you should also add a unique index to the table in the database. This will provide two immediate benefits:
The validation check and any searches through this model based on these two id's will perform faster (since they're indexed)
The uniqueness constraint will be enforced DB-side, and on the rare occurrence of a race condition you won't get bad data saved to the database... although users will get a 500 Server Error if you don't catch the error.
In a migration file add the following:
add_index :enrollments, [:patient_id, :client_id], :unique => true
Hopefully this was helpful :)
Edit (fixed some naming issues and a couple obvious bugs):
It's then very easy to find the data you're looking for:
Client.find_by_name("Bob Smith").patients
Patient.find_by_name("Henry Person").clients
Validations would work (Back them up with a unique index!), but there's no way to get a true composite primary key in vanilla Rails. If you want a real composite primary key, you're going to need a gem/plugin - composite_primary_keys is the one I found, but I'm sure there are others.
Hope this helps!
Add a UNIQUE constraint to your table across the two columns. Here's a reference for MySQL http://dev.mysql.com/doc/refman/5.0/en/constraint-primary-key.html

Resources