not sure how to model in ActiveRecord - ruby-on-rails

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.

Related

Object that belongs to multiple other objects

Take the following associations based on a Feedback model:
feedback.rb
belongs_to :buyer, :foreign_key => :buyer_id, :class_name => "User"
belongs_to :seller, :foreign_key => :seller_id, :class_name => "User"
belongs_to :listing
The reverse associations are has_many
When creating the feedback object it could be 'anchored' to any of the above other objects (e.g. buyer.feedbacks, seller.feedbacks, listing.feedbacks)
Say in this example we want to primarily link it with the buyer and so nest the feedback routes within user and then build a create action in the Feedbacks controller that looks something like:
current_user.feedbacks.new(feedback_params)
or is it more appropriate/correct to reference?
buyer.feedbacks.new(feedback_params)
Is this even valid without an explicit buyer model?
What is the Rails way to then incorporate the other belongs_to relationships?
It's not a nested attribute (as the other objects already exist).
Should I be merging in the other params with something like?
params.require(:feedback).permit(:rating, :comment).merge(seller_id: #seller.id, listing_id: #listing.id)
One approach I have seen is the use of a before_validation filter in this sort of manner (from a different domain) like this:
class Feedback < ActiveRecord::Base
belongs_to :user
belongs_to :host, :class_name => "User"
belongs_to :inquiry
belongs_to :room
before_validation :set_room_and_guest_id
def set_room_and_guest_id
self.room ||= self.inquiry.room if self.inquiry
self.user ||= self.inquiry.user if self.inquiry
end
I have spent a long time reading related posts about this today as well as the Rails documentation and have not been able to find a conclusion.
There's no "right" way here - just build the system you want. It sounds like a Buyer has Feedback about a Listing sold by a Seller, so it's completely reasonable to link all of those things together (or at least Amazon hasn't discovered a reason not to yet, and that's a pretty good sign).
The simplest "Rails way" you're probably looking for is to include all the relevant IDs in the feedback form. That does make them accessible to people who might want to fiddle, eg. by setting the seller/listing IDs to their own and leaving fraudulent positive feedback. You can combat that by merging #seller and #listing in the controller like you've mentioned, or with validations that the reviewer has bought the item, can't leave more than one, etc.
It also sounds like there might be room for a Transaction object here, representing the link between Buyer, Seller and Listing. Maybe the Feedback belongs on the Transaction.
Overall, I'd say you've been paralyzed by all the options available to you, and the best thing to do is pick one and run with it. When it's not clear which direction is best, that's often because you don't have all the information you need yet, but once you try something out you'll quickly learn more. Once you realize "Oh, I should have done this this other way", the beauty of code is you can change it.
I assume every listing has exactly one buyer and one seller, and there can be exactly zero or one feedbacks per listing. Then you might be confusing things a bit by linking the feedback directoy to buyer and seller. The normalized way would be to relate the feedback to the listing and nothing else. Then all questions go away.
(Note, you can then still get the buyer (or seller) directly from the feedback by using a :through rails relation.)
Maybe you are looking for Polymorfic Associations.
A slightly more advanced twist on associations is the polymorphic association. With polymorphic associations, a model can belong to more than one other model, on a single association.

Is there a different association that behaves like belongs_to?

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.

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.

How to handle associated objects of a `has_many :through` association?

I am using Ruby on Rails 3.2.2 and I would like to know what is a common approach in order to handle associated objects of a has_many :through ActiveRecord::Association. That is, I have:
class User < ActiveRecord::Base
has_many :article_editor_associations, :class_name => 'Articles::UserEditorAssociation'
has_many :articles, :through => :article_editor_associations
end
class Article < ActiveRecord::Base
has_many :user_editor_associations, :class_name => 'Articles::UserEditorAssociation'
has_many :editor_users, :through => :user_editor_associations
end
class Articles::UserAssociation < ActiveRecord::Base
belongs_to :editor_users
belongs_to :articles
end
By using the above code, I can run the #article.editor_users method so to retrieve an Array of Editor Users. However, in order to make things to fit better with my application (that is, for example, in order to handle things like I18n translations and similar in a "programmatic" way), I am thinking to add to my application a new model like the following:
class EditorUser < User # Note the class name and the class inheritance
...
end
This way, through my application, I can refer to the EditorUser class in order to handle article "editor user" instances as if they were User objects... more, since inheritance, in the EditorUser class I can state "specific methods" (for example, scope methods) available only to EditorUser instances (not to User instances)...
Is it a "common" approach to make things as I would like to make in my case? Is it the "Rails Way"? If so, what I could / should make to handle this situation? If no, how could / should I proceed?
In other words, I thought using class EditorUser < User ... end because associated EditorUser objects (retrieved by running the #article.editor_users method) are User objects. I think that by stating a EditoUser class in the app/models directory (or elsewhere) could simplify things in my application because you can work around that constant name (for example, you can "play" with that constant name in order to "build" translation strings or by stating new methods just to be used for EditorUser instances).
With Rails, I've learned to focus on the naming conventions and standard usage first ('convention' over configuration) and would set it up like this:
class User < ActiveRecord::Base
has_many :editors
has_many :articles, :through => :editors
end
class Article < ActiveRecord::Base
has_many :editors
has_many :users, :through => :editors
end
class Editor < ActiveRecord::Base
belongs_to :user
belongs_to :article
end
You can either use the presence of the join record, e.g. User.editor or add an additional attribute to editor if you want different editor access levels.
The above does not fully answer your question perhaps but should be a good starting point. I say this because one of the most important things about rails is that it uses a principle of 'convention over configuration'. This is good as it leads to terse, minimalist code. It's bad because you have to learn all the zillion conventions. If you don't know them or the framework well you can get yourself into a whole heap of trouble as I have seen with many rails applications that I have worked on over the years.
So my advice is really to step back. Don't try and force things to work with things like class renames. If the setup I have shown doesn't meet your needs, revisit your needs and read more on active record and associations in the API. I know this can be kinda frustrating for quite a while with rails but you really need to look how to do things the right way if you're going to be a good rails programmer in the long term.

Rails: Many to many polymorphic relationships

See comments for updates.
I've been struggling to get a clear and straight-forward answer on this one, I'm hoping this time I'll get it! :D
I definitely have a lot to learn still with Rails, however I do understand the problem I'm facing and would really appreciate additional help.
I have a model called "Task".
I have an abstract model called "Target".
I would like to relate multiple instances of subclasses of Target to Task.
I am not using single table inheritance.
I would like to query the polymorphic relationship to return a mixed result set of subclasses of Target.
I would like to query individual instances of subclasses of Target to obtain tasks that they are in a relationship with.
So, I figure a polymorphic many to many relationship between Tasks and subclasses of Targets is in order.
In more detail, I will be able to do things like this in the console (and of course elsewhere):
task = Task.find(1)
task.targets
[...array of all the subclasses of Target here...]
But! Assuming models "Store", "Software", "Office", "Vehicle", which are all subclasses of "Target" exist, it would be nice to also traverse the relationship in the other direction:
store = Store.find(1)
store.tasks
[...array of all the Tasks this Store is related to...]
software = Software.find(18)
software.tasks
[...array of all the Tasks this Software is related to...]
The database tables implied by polymorphic relationships appears to be capable of doing this traversal, but I see some recurring themes in trying to find an answer which to me defeat the spirit of polymorphic relationships:
Using my example still, people appear to want to define Store, Software, Office, Vehicle in Task, which we can tell right away isn't a polymorphic relationship as it only returns one type of model.
Similar to the last point, people still want to define Store, Software, Office and Vehicle in Task in one way shape or form. The important bit here is that the relationship is blind to the subclassing. My polymorphs will initially only be interacted with as Targets, not as their individual subclass types. Defining each subclass in Task again starts to eat away at the purpose of the polymorphic relationship.
I see that a model for the join table might be in order, that seems somewhat correct to me except that it adds some complexity I assumed Rails would be willing to do away with. I plea inexperience on this one.
It seems to be a small hole in either rails functionality or the collective community knowledge. So hopefully stackoverflow can chronicle my search for the answer!
Thanks to everyone who help!
You can combine polymorphism and has_many :through to get a flexible mapping:
class Assignment < ActiveRecord::Base
belongs_to :task
belongs_to :target, :polymorphic => true
end
class Task < ActiveRecord::Base
has_many :targets, :through => :assignment
end
class Store < ActiveRecord::Base
has_many :tasks, :through => :assignment, :as => :target
end
class Vehicle < ActiveRecord::Base
has_many :tasks, :through => :assignment, :as => :target
end
...And so forth.
Although the answer proposed by by SFEley is great, there a some flaws:
The retrieval of tasks from target (Store/Vehicle) works, but the backwards wont. That is basically because you can't traverse a :through association to a polymorphic data type because the SQL can't tell what table it's in.
Every model with a :through association need a direct association with the intermediate table
The :through Assignment association should be in plural
The :as statement wont work together with :through, you need to specify it first with the direct association needed with the intermediate table
With that in mind, my simplest solution would be:
class Assignment < ActiveRecord::Base
belongs_to :task
belongs_to :target, :polymorphic => true
end
class Task < ActiveRecord::Base
has_many :assignments
# acts as the the 'has_many targets' needed
def targets
assignments.map {|x| x.target}
end
end
class Store < ActiveRecord::Base
has_many :assignments, as: :target
has_many :tasks, :through => :assignment
end
class Vehicle < ActiveRecord::Base
has_many :assignments, as: :target
has_many :tasks, :through => :assignment, :as => :target
end
References:
http://blog.hasmanythrough.com/2006/4/3/polymorphic-through
The has_many_polymorphs solution you mention isn't that bad.
class Task < ActiveRecord::Base
has_many_polymorphs :targets, :from => [:store, :software, :office, :vehicle]
end
Seems to do everything you want.
It provides the following methods:
to Task:
t = Task.first
t.targets # Mixed collection of all targets associated with task t
t.stores # Collection of stores associated with task t
t.softwares # same but for software
t.offices # same but for office
t.vehicles # same but for vehicles
to Software, Store, Office, Vehicle:
s = Software.first # works for any of the subtargets.
s.tasks # lists tasks associated with s
If I'm following the comments correctly, the only remaining problem is that you don't want to have to modify app/models/task.rb every time you create a new type of Subtarget. The Rails way seems to require you to modify two files to create a bidirectional association. has_many_polymorphs only requires you to change the Tasks file. Seems like a win to me. Or at least it would if you didn't have to edit the new Model file anyway.
There are a few ways around this, but they seem like way too much work to avoid changing one file every once in a while. But if you're that dead set against modifying Task yourself to add to the polymorphic relationship, here's my suggestion:
Keep a list of subtargets, I'm going to suggest in lib/subtargets formatted one entry per line that is essentially the table_name.underscore. (Capital letters have an underscore prefixed and then everything is made lowercase)
store
software
office
vehicle
Create config/initializers/subtargets.rb and fill it with this:
SubtargetList = File.open("#{RAILS_ROOT}/lib/subtargets").read.split.reject(&:match(/#/)).map(&:to_sym)
Next you're going to want to either create a custom generator or a new rake task. To generate your new subtarget and add the model name to the subtarget list file, defined above. You'll probably end up doing something bare bones that makes the change and passes the arguments to the standard generator.
Sorry, I don't really feel like walking you through that right now, but here are some resources
Finally replace the list in the has_many_polymorphs declaration with SubtargetList
class Task < ActiveRecord::Base
has_many_polymorphs :targets, :from => SubtargetList
end
From this point on you could add a new subtarget with
$ script/generate subtarget_model home
And this will automatically update your polymorphic list once you reload your console or restart the production server.
As I said it's a lot of work to automatically update the subtargets list. However, if you do go this route you can tweak the custom generator ensure all the required parts of the subtarget model are there when you generate it.
Using STI:
class Task < ActiveRecord::Base
end
class StoreTask < Task
belongs_to :store, :foreign_key => "target_id"
end
class VehicleTask < Task
belongs_to :vehicle, :foreign_key => "target_id"
end
class Store < ActiveRecord::Base
has_many :tasks, :class_name => "StoreTask", :foreign_key => "target_id"
end
class Vehicle < ActiveRecord::Base
has_many :tasks, :class_name => "VehicleTask", :foreign_key => "target_id"
end
In your databse you'll need:
Task type:string and Task target_id:integer
The advantage is that now you have a through model for each task type which can be specific.
See also STI and polymorphic model together
Cheers!
This may not be an especially helpful answer, but stated simply, I don't think there is an easy or automagic way to do this. At least, not as easy as with simpler to-one or to-many associations.
I think that creating an ActiveRecord model for the join table is the right way to approach the problem. A normal has_and_belongs_to_many relationship assumes a join between two specified tables, whereas in your case it sounds like you want to join between tasks and any one of stores, softwares, offices, or vehicles (by the way, is there a reason not to use STI here? It seems like it would help reduce complexity by limiting the number of tables you have). So in your case, the join table would also need to know the name of the Target subclass involved. Something like
create_table :targets_tasks do |t|
t.integer :target_id
t.string :target_type
t.integer :task_id
end
Then, in your Task class, your Target subclasses, and the TargetsTask class, you could set up has_many associations using the :through keyword as documented on the ActiveRecord::Associations::ClassMethods rdoc pages.
But still, that only gets you part of the way, because :through won't know to use the target_type field as the Target subclass name. For that, you might be able to write some custom select/finder SQL fragments, also documented in ActiveRecord::Associations::ClassMethods.
Hopefully this gets you moving in the right direction. If you find a complete solution, I'd love to see it!
I agree with the others I would go for a solution that uses a mixture of STI and delegation would be much easier to implement.
At the heart of your problem is where to store a record of all the subclasses of Target. ActiveRecord chooses the database via the STI model.
You could store them in a class variable in the Target and use the inherited callback to add new ones to it. Then you can dynamically generate the code you'll need from the contents of that array and leverage method_missing.
Have you pursued that brute force approach:
class Task
has_many :stores
has_many :softwares
has_many :offices
has_many :vehicles
def targets
stores + softwares + offices + vehicles
end
...
It may not be that elegant, but to be honest it's not that verbose, and there is nothing inherently inefficient about the code.

Resources