Is there a different association that behaves like belongs_to? - ruby-on-rails

I'm new to rails and I'm trying to associate a default song with a theme. The problem is if I give the theme a default_song_id attribute, I can only access the song directly with a call to default_song if I make the theme belong_to the song.
My problem with this is basically just the name of the association. The theme obviously doesn't belong to the song in the hierarchy of my models, and the songs have too many attributes already. It doesn't make sense to give songs a theme_id attribute as the songs are involved in plenty of other relations and it really is just the theme that cares about a particular song, plus one song can be referenced by multiple themes.
So do I have any other options?

It sounds as though the 'has_many :through' association might be what you're looking for. There's a great run-through here: http://guides.rubyonrails.org/association_basics.html.
Essentially, you're going to want to set up an intermediary model to join your Song and Theme models without making one explicitly belong to the other. Say you create an "Assignment" model to handle this, your models would say:
class Song < ActiveRecord::Base
has_many :assignments
has_many :themes, through: :assignments
end
class Theme < ActiveRecord::Base
has_many :assignments
has_many :songs, through: :assignments
end
class Assignment < ActiveRecord::Base
belongs_to :song
belongs_to :theme
end
For each pairing you then have an Assignment with a theme_id and a song_id so you can always query the Assignments table where theme_id/song_id = x to retrieve either associated record. Hopefully this approach is flexible enough to do what you're trying to do.

As concerns using another name for the association definition: No.
Rails is an opinionated framework, by design - convention over configuration. belongs_to is the keyword its designers have chosen for this concept in the DSL of model/association descriptions, and you should try to get used to using it. Try to keep in mind that what you're writing is still code; just because a lot of Ruby/Rails reads like English, that does not mean it is English, and keywords aren't always going to have the same meaning as the English words they look like.
It is theoretically possible to alias belongs_to and the other association macros, but you really shouldn't. It will harm the readability of your code if anyone else ever has to use it.

Related

Conditionally activate "acts_on_list" when field is defined

I have a model "entry" and I need it to act like a list when a playlist_id is specified, but if it's not, I need it to not act like a list. (acts_as_list is a gem I'm using)
In my model code I have:
acts_as_list scope: :playlist
I need to figure out the best way to do this. I'm thinking of subclassing a model maybe, but I'd prefer to just keep it as one model but add this additional logic. I don't know the order of initialization for active_record so I'm not sure where I could mess with things like this and where I can't.
(The reason why I need to do this: I want to have loose items that belong to another model, simply sorted by date. As my "default list" has grown in size, I'm experiencing some performance issues since we have to look up the last entry in a list to know the position of the newest item.)
My shallow understanding is the model projection may need improvement. In my understanding act_as_list is better for has_many - belongs_to relationship, say a todo is exactly in a Todo list.
But in your case, let's say the entry is a song. A playlist can have many songs and a song can belongs to many playlist. So the relationship is many to many.
I think you need an intermediate model say ListItem to represent such relationship
class PlayList < ActiveRecord::Base
has_many :list_items
has_many :entries, through: :list_items
end
class ListItem < ActiveRecord::Base
belongs_to :play_list
belongs_to :entires
acts_as_list scope: :play_list
end
class Entries < ActiveRecord::Base
has_many :list_items
has_many :play_lists, through: :list_items
By this design, what you sort on PlayList is only the list items, not the entries. Performance should be improved a lot as longs as on playlist doesn't contain too much list_items, which should be common.

Should I use `has_and_belongs_to_many` or `has_many :through` in my model?

I have read the Choosing Between has_many :through and has_and_belongs_to_many on the Rails website, however I am a bit confused since I have a different case to the ones given on the website.
I have two models: Prop and CharacterCostume, and the character's costume can have multiple props associated to it, but a prop doesn't belong to that character and it can be used by any number of characters in the scene, too.
Right now I have has_and_belongs_to_many :props inside my CharacterCostume model, which does exactly what I want it to do: it fetches all the props associated with the costume using a table named character_costumes_props when I call CharacterCostume#props
However the association name is putting me off because of the "belongs to many" part. The costume does not belong to any of the props, so there's no has_and_belongs_to_many :character_costumes inside the Prop model.
I know that it can all function fine without it, but it got me thinking that maybe I should use a has_many :through association, but that requires me to create a superfluous model (it is superfluous, right?) and the model would look like this:
class CharacterCostumeProp < ActiveRecord::Base
belongs_to :character_costume
has_one :prop
end
Also, would has_one instead of belongs_to work here?
I want the code to be as semantic as possible, but I am not sure if this will increase the requirement for resources or decrease performance in some way, since there's an intermediate model.
Are there certain quirks/benefits attached to either approach? Is mine good enough? Or is my thinking completely wrong from what I need to do?
Thanks!
I think you want to use a :has_many, :through because you're going to want to work directly with the relation model - what scene(s), consumed or damaged, etc.
But, the reason it reads funny to you is that, for the most part, has_many and belongs_to don't really mean what they mean in English. What they really mean is "They have the foreign keys" and "I have the foreign key", respectively; the exception being the :dependent => :destroy behavior.
That still doesn't really help with has_and_belongs_to_many, since you're then saying, "They have the foreign keys and I have the foreign keys` - except that you can think of it sort of adding a new part both to "I" and "They" that happens to be the same part for each, and has those keys.
Does that help?
The single most important question you must ask yourself when deciding between HABTM and has_many :through is this:
Do I want to store any information specific to the association?
Example 1: magazine subscriptions
A many-to-many relationship between readers and magazines might conceivably be structured as a HABTM or a has_many :through. However, the latter makes far more sense in this case because we can easily think of information specific to the association that we might want to store.
A reader is related to a magazine through a subscription, and every subscription can be described by fields such as price, starting date, issue frequency and whether it's active or not.
Example 2: tags
The relationship between an existing Tag model and, say, an Article model is clearly of the many-to-many kind. The fact that one particular tag has been associated to any particular article must have no influence on whether the same tag will be able to be similarly associated to other articles in the future.
But, differently from the previous example, here the association itself is all the information we need. We just need to know which tags are associated to any given article. It doesn't matter when the association was formed. It doesn't matter how long it lasted.
It may matter to us how many articles a tag is associated with. But that information is stored in the Tag model since it's not specific to an association. There is even a Rails feature that takes care of that called counter_cache.
has_one wouldn't work, you'd need belongs_to
it is not superfluous if you have logic in your association model
has_and_belongs_to_many is good enough for you
See example below
class Student
has_and_belongs_to_many :courses
has_many :teachers, through: :courses
end
class Teacher
has_many :courses
has_many :students, through: :courses
end
class Course
has_and_belongs_to_many :students
belongs_to :teacher
def boring?
teacher.name == 'Boris Boring'
end
end
In the example above, I make use of both versions. See how Course would have its own logic? See how a class for CourseStudent might not? That's what it all comes down to. Well, to me it is. I use has_many through for as long as I can't give a proper name to my association model and/or the model doesn't need extra logic or behavior.

Modelling an application in Rails - mixing STI and polymorphic associations

Please forgive me if this has been answered already but I've searched a lot and still require some clarification.
I'm building a Property Management tool using Rails 3.2. I already have a User model and authorisation/authentication code in place with full tests coverage.
I've just started drawing out the models/classes/tables and have gotten myself a bit confused.
Let's start with Users.
Modelling Users
I plan to have allow multiple companies to use this system. Each will have employees (users). These users will have different roles e.g. Manager, Agent, Accountant, Secretary etc. For the most part the data I plan to store for each of these users will be similar (or so I think at the moment) so I am leaning towards Single Table Inheritance and using the type to define the level of access each employee has.
Secondly, I plan to allow Landlord and Tenants to also log in to the system. Upon logging in they'll be able to view information about the property they are owning or renting - maybe keep their contact details up to date too.
I was thinking of using polymorphic associations to represent these users.
So the plan I have at the moment and would like some feedback on is to have
User < ActiveRecord::BASE
Employee < User (this will have a STI type column and allow for the different employee roles)
Landlord < User
Tenant < User
Is this the best way of approaching this problem or am I shooting myself in the foot?
I've had some people advise me I should have a 'roles' table and assign roles to the users - but I have a feeling this isn't the most elegant way to do this in Rails.
Properties
My next issue is with Properties. Right now I have a model for properties and when I add them they belong_to a User (i.e. they have a user_id foreign key). I then started thinking "what happens if the employee (user) that added the Property leaves the company or has their account deleted for some reason?"
So in this scenario is it best to forgo the User/Employee to Property association and just link the Property to the Company that the employee belongs to? This way I can all employee.company.properties to list out all the properties?
Landlord and Tenant associations
Let's presume we make Properties belong to a Company.
In terms of associations this is what I have in my head. Looking at it now I see that everything belongs to a company because one company using the system shouldn't be able to see the landlords/tenants/employees/properties of another company.
class Landlord < User
belongs_to :company
has_many :properties, :through => :ownerships
end
class Tenant < User
belongs_to :company
has_one :property, :through => tenancies #you can only live at one place at a time right?
end
class Property < ActiveRecord::Base
has_many :tenants, :through => :tenancies
has_many :landlords, :through => :ownerships
belongs_to :company
end
class Company < ActiveRecord::Base
has_many :properties
has_many :employees
has_many :landlords :through => :ownerships #not sure if through is required/works here
has_many :tenants :through => :tenancies #not sure if through is required/works here
end
class Employees < User
belongs_to :company
end
Properties
Also I'm guessing we'll have different types of Properties (Commercial/Residential) and of those there will be whole buildings, apartments within a building (single address) etc.
Like with users I'm planning on using Polymorphic Associations to define two subclasses CommercialProperty and ResidentialProperty and then use sti to define a type. If the type is "multi unit" then have a new model for units and an association whereby Property has_many Units and a Unit belongs_to a property.
Aim
I'm trying to make sure that my code follows best practice as much as possible so that when I come to add new features and expand I'm not left having to re-write large chunks of the app.
I would really appreciate your feedback.
Reference
Some of the posts I've read. Hopefully to help others trying to solve the same problem.
Designing a Rails application: single table inheritance?
Ruby on rails with different user types
Ruby On Rails User Model for multiple types
It's probably too late but you could also use has_and_belongs_to_many on User and Company and thus avoid STI altogether by using gems cancan and rolify.
It allows you to define finely grained access rights (abilities).
I know that it seems more elegant having different classes instead of roles, but it is not viable long-term strategy, it can become messy when logic becomes complex.
Other then that, the rest seems pretty solid, hope that helps :)

Multiple Table Inheritance vs Polymorphic

I’m creating an app that allows a user to create a course and include different types of resources (document, video, quiz) in the course. I’m having a hard time figuring out the best way to set up association between a course and its resources.
Right now, I have:
class Course < AR::Base
has_many :documents
has_many :videos
has_many :quizzes
end
class Document <AR::Base
belongs_to :course
end
class Video <AR::Base
belongs_to :course
end
class Quiz <AR::Base
belongs_to :course
end
Documents, Videos, and Quizzes all have some common attributes (e.g., name, description) but also many attributes that differ. I considered using STI and having them inherit from a single class called “Lessons.” I decided against this approach because I need multiple controllers for each class.
Ultimately, I want to be able to perform operations on all the resources that belong to a course so for example list all the documents, videos, and quizzes together and display them as a sortable list.
Any suggestions on how best to set up this model. It seems as if I could do it two ways:
Reverse polymorphic has_one association (see example)
Multiple Table inheritance (see example)
I’m a rails noob so I’m having a hard time evaluating which approach is best for this situation. Any advice would be appreciated!
Ultimately, I want to be able to perform operations on all the resources that belong to a course so for example list all the documents, videos, and quizzes together and display them as a sortable list.
Either approach is doable, but when I read this requirement, it seems you'd be best off with STI. STI is a natively supported feature in rails and allows you to query and manipulate different types of resources within the same collection.

not sure how to model in ActiveRecord

I am making a simple event system (like physical events, not software events). It has the following structure. Each event will have a set of slots (think a music event, opening act, healiner etc...). Each event_slot will be a reference to a tag. Right now I have the following but I think this is not going to work:
class Event < ActiveRecord::Base
#id primary key
has_many :event_slots, :order => "sort desc"
has_many :tags, :through => :event_slots
end
# event_slots will be populuated with tag_id
class EventSlot < ActiveRecord::Base
# event_id, tag_id; will also have a sort value to sort these
belongs_to :event
belongs_to :tag
end
the issue is that event_slots will have a tag_id. In other words we'll be adding the tags and associating them in place (like physically in place in a web form).
class Tag < ActiveRecord::Base
has_many :event_slots
end
I am not sure if this modeling will work. Any ideas on how to implement / improve this this? The has_many :through seems not be done correctly.
thx
That should work fine. I would perhaps try use a better name than EventSlots because its not intuitive what it represents. If its aimed at the music market something like Acts would perhaps make more sense.
Using something like accepts_nested_attributes_for on the Event model can help eliminate the need for a controller for the second nested model (Act/EventSlot). Take a look at http://railscasts.com/episodes/196-nested-model-form-part-1 if you havent already.
Lastly I would consider not rolling your own tagging system. There are already plenty of well tested gems you can use to provide the functionality you need. Check out https://www.ruby-toolbox.com/categories/rails_tagging.html to find one that might suit your needs.

Resources