In my app I have following models:
belong_to a list.
belongs_to a category.
Each list of items also needs to be somehow associated with multiple categories. Meaning that if user creates a category it will have a
list_id assign to it that is equal to
id of the list user was working on when the category was created. That way when user decides to get rid of the list I can also get rid of all of the custom categories that were created for that list. The problem is that I would also like to have some "default" categories: ones that are available for all of the lists. I am not sure how to model relationship between
belongs_to is not working for me because "default" categories don't really belong to any specific list, they belong to all of the lists.
I would greatly appreciate any suggestion on how to handle that type of relationship!
You definitely need
has_many relation on the both sides of
You can keep category names that are the "defaults" in a constant inside the category model or the category can have boolean attribute so that you know whether to delete it or not.
To delete a category when a list is deleted you'll probably need to write a custom method that may run as an
after_destroy callback on the List model.
You want to set up a Many to Many relationship for your Category and List models. To do that this is what you would do
class List < ActiveRecord::Base has_many :categorizations, dependent: :destroy has_many :categories, :through => :categorize end class Categorization < ActiveRecord::Base belongs_to :category belongs_to :list end class Category < ActiveRecord::Base has_many :categorizations, dependent: :destroy has_many :lists, :through => :categorizations end class Item < ActiveRecord::Base belongs_to :category belongs_to :list end
This will create a third table to keep track of the relationships between all the models. Ryan Bates has a great railscast on this subject you should probably check out.
dependent: :destroy will ensure that if one is deleted so is the relationship and then to ensure the other categories are deleted from that list you can use a before_destroy or after_destroy method.