I've read in various places that it gets automatically inferred in some circumstances, but I've found the documentation on this feature to be hard to follow. Can anyone shed some light on the principles? Specifically when will Rails be able to infer and when will Rails not be able infer inverses?
I'd like to consider
polymorphic associations
single tabled inheritance (e.g. where BundleProduct and IndividualProduct both inherit from Product and use a products table)
regular has_one/has_many/belongs_to associations
has many through: associations
Some context: I'm maintaining a reasonably large 9-year-old Rails application with many, many tables. I'd like to have some guidance on which models require addition of inverse_of: rather than having to change every model in the system.
If you do not set the :inverse_of record, the association will do its
best to match itself up with the correct inverse. Automatic inverse
detection only works on has_many, has_one, and belongs_to
associations.
-- Rails API docs - ActiveRecord::Associations::ClassMethods
In cases where you have "non-standard" naming you may however need to provide the option:
The automatic guessing of the inverse association uses a heuristic
based on the name of the class, so it may not work for all
associations, especially the ones with non-standard names.
-- Rails API docs - ActiveRecord::Associations::ClassMethods
For example:
class Pet < ApplicationRecord
belongs_to :owner, class_name: 'User'
end
class User < ApplicationRecord
has_many :pets
end
If we call pet.owner it may incur a database hit even if we have already loaded that record.
If we add the inverse_of option:
class Pet < ApplicationRecord
belongs_to :owner, class_name: 'User', inverse_of: :pets
end
class User < ApplicationRecord
has_many :pets, inverse_of: :owner
end
Now if we already have that owner record in memory then pet.owner will point to the same owner.
In general there is no harm in explicitly setting the inverse_of so you can set it for each case where you are unsure. You can also manually test if it is needed by seeing if accessing the assocation creates a DB query via the console or by using shoulda-matchers with your test suite.
You can look up exact inferring procedure in ActiveRecord::Reflection::AssociationReflection#automatic_inverse_of.
Rails tries to detect inverse for has_many, has_one and belongs_to that do not have through, foreign_key options and scope and have standard names (this is also described in official guide).
Related
I have a polymorphic table in rails MetaFieldsData which also belongs to a table MetaFields
class MetaFieldsData < ApplicationRecord
belongs_to :owner, polymorphic: true
belongs_to :meta_field
end
class MetaField < ApplicationRecord
belongs_to :organization
has_many :meta_fields_data
end
One model which is connected to the polymorphic table is called orders:
class Order < ApplicationRecord
belongs_to :organization
...
has_many :meta_fields_data, as: :owner
...
owner is my association class (the same what is imageable from the official RoR guide)
Now I see a strange behaviour when I want to create a record on a the Order model:
MetaFieldsData.create(owner: order, meta_field: some_meta_field)
It throws:
NameError Exception: Rails couldn't find a valid model for MetaFieldsDatum association.
Please provide the :class_name option on the association declaration. If :class_name is already provided, make sure it's an ActiveRecord::Base subclass.
What is weird is that there is no class MetaFieldsDatum (note the typo here, coming from Rails). I searched all my code and there is no typo in there, also not in the class name definition.
This makes it impossible for me to create an actual MetaFieldsData on this table as Rails seems to interpret the naming wrong.
What could possibly be wrong here?
Thank you
I had the same problem, but my solution was different.
I had a typo in my belongs_to model which invalidated the model.
I discovered it was an invalid model by trying to access it in the console. Because it was invalid, Rails didn't load it and subsequently couldn't find it.
The error disappeared when I corrected the typo.
Datum is used as a plural form of data. Notice that you have has_many :meta_fields_data and if you would to change that into a singular it would also be has_one :meta_fields_data.
This is called inflection and it is a way of detecting plural forms of words, you can read up on how rails does it here https://api.rubyonrails.org/classes/ActiveSupport/Inflector/Inflections.html
In general you can either simply obide to what the error tells you and use datum in relationship name (specify class_name if you do so), or define your own inflection
I have two models with the following associations:
organization.rb
class Organization < ActiveRecord::Base
has_one :user, as: :identifiable
has_many :speakers
#has_many :cast_items
end
speaker.rb
class Speaker < ActiveRecord::Base
has_one :user, as: :identifiable
#has_many :cast_items
end
As you can see, I've commented out an association with the CastItem model.
I want a Speaker to add multiple CastItems. Also, an Organization must be able to add multiple CastItems. When an Organization adds a CastItem, it does not necessarily belongs to a Speaker who is associated with an Organization. In other words an organization must be able to add a CastItem to itself or to a Speaker who is associated with him.
Will it be completely valid to put the has_many :cast_items in both models, or are there more practical design options?
Yes, you can do that. Remember to add organization_id and speaker_id to your cast_items model.
You can check out this link, http://guides.rubyonrails.org/association_basics.html , some useful information regarding many to many and one to many associations.
Personally, in your case, I will use has_many :through
You can definitely do that. I can't think of any reason that would be bad and it's often necessary.
You may want to look up the 'delegate' method for when you're creating CastItems, and have them always created by Organizations.
Also, make sure that if you have a :speaker_id on your CastItem that it can accept nil or false.
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.
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.
Rails has a has_one :through association that helps set up a one-to-one association with a third model by going through a second model. What is the real use of that besides making a shortcut association, that would otherwise be an extra step away.
Taking this example from the Rails guide:
class Supplier < ActiveRecord::Base
has_one :account
has_one :account_history, :through => :account
end
class Account < ActiveRecord::Base
belongs_to :supplier
has_one :account_history
end
class AccountHistory < ActiveRecord::Base
belongs_to :account
end
might allow us to do something like:
supplier.account_history
which would otherwise be reached as:
supplier.account.history
If it's only for simpler access then technically there could be a one-to-one association that connects a model with some nth model going through n-1 models for easier access. Is there anything else to it that I am missing besides the shortcut?
Logic, OK it might sound a bit weak for this but it would be logical to say that "I have a supplier who has an account with me, I want to see the entire account history of this supplier", so it makes sense for me to be able to access account history from supplier directly.
Efficiency, this for me is the main reason I would use :through, simply because this issues a join statement rather than calling supplier, and then account, and then account_history. noticed the number of database calls?
using :through, 1 call to get the supplier, 1 call to get account_history (rails automatically uses :join to retrieve through account)
using normal association, 1 call to get supplier, 1 call to get account, and 1 call to get account_history
That's what I think =) hope it helps!
I'm surprised no one has touched on Association Objects.
A has_many (or has_one) :through relationship facilitates the use of the association object pattern which is when you have two things related to each other, and that relation itself has attributes (ie a date when the association was made or when it expires).
This is considered by some to be a good alternative to the has_and_belongs_to_many ActiveRecord helper. The reasoning behind this is that it is very likely that you will need to change the nature of the association or add to it, and when you are a couple months into a project, this can be very painful if the relationship were initially set up as a has_and_belongs_to_many (the second link goes into some detail). If it is set up initially using a has_many :through relationship, then a couple months into the project it's easy to rename the join model or add attributes to it, making it easier for devs to respond to changing requirements. Plan for change.
Inverse association: consider the classic situation user-membership-group. If a user can be a member in many groups, then a group has many members or users, and a user has many groups. But if the user can only be a member in one group, the group still has many members: class User has_one :group, :through => :membership but class Group has_many :members, :through => memberships. The intermediate model membership is useful to keep track of the inverse relationship.
Expandability: a has_one :through relationship can easy be expanded and extended to a has_many :through relationship