Search code examples
ruby-on-railsrubyactivemodel

ActiveModel: proper relation for a different type of the resource


I'm trying to determine the proper ActiveModel realtionship for the following situation: there are pictures and there are different categories of them: foo, bar, baz and qux. A User can set one like and several comments per the picture. I started with a Catregory and a Foo models. The simpliest approach could be - creatation of likes and comments properties for each of the Foo, Bar, Baz and Qux models. But I feel it's a silly approach... There might be a better one. What is the best kind of realationship can be chosen for such a case?


Solution

  • Here's what I imagined reading your question (I've decided that your pictures were created by users, because your model looks a lot like a social network):

    class User < ActiveRecord::Base
      has_many :pictures
      has_many :comments
      has_one :like
    end
    
    class Picture < ActiveRecord::Base
      belongs_to :user
      belongs_to :category
      has_many :likes
      has_many :comments
    end
    
    class Category < ActiveRecord::Base
      has_many :pictures
    end
    
    class Comment < ActiveRecord::Base
       belongs_to :user
       belongs_to :picture
    end
    
    class Like < ActiveRecord::Base
       belongs_to :user
       belongs_to :picture
    end
    

    Categories are rows of the categories Table. Instead of making one Model per category, you should have one model Category for all of them, with attributes like name, color or whatever you want.