Search code examples
ruby-on-rails-3activerecordrefinerycmsactive-relation

Link two models through middlemodel at Rails 3.x


I guess that I do not know the right terminology yet, thus find it difficult to find the right answer.

So, I have created an engine with Exhibit and Category. I created a third model Categorization so as to assign an exhibit to more than one categories. This has only the exhibit_id and category_id.

What I want to do is to create a page for every category, so I assign an exhibit to the News category, to display it in the "News" page, when to the Photographs category to display it in the "Photographs" page etc. I guess this is a routing configuration, but I have not got there yet (however, please let me know if it is indeed a routing configuration)

My problem is how to retrieve the fields from different models, from only one controller. What I have:

class Categorization < ActiveRecord::Base
  belongs_to :exhibit
  belongs_to :category
end

class Category < ActiveRecord::Base
  has_many :categorizations
  has_many :exhibits, :through => :categorizations
  acts_as_indexed :fields => [:title]
  validates :title, :presence => true, :uniqueness => true 
end

class Exhibit < ActiveRecord::Base
  has_many :categorizations
  has_many :categories, :through => :categorizations, :source => :category
  acts_as_indexed :fields => [:title, :bulb]
  validates :title, :presence => true, :uniqueness => true
  belongs_to :foto, :class_name => 'Image'
end

How do i retrieve the :foto of the Exhibit, which belongs to :category =>"News"?

I tried to add scope :news, where(['category_id="1"']) in Categorization model and i can retrieve Categorization.news but how do I connect the Categorization.exhibit_id with the photo of this exhibit (I guess this is Exhibit.foto)?

I don't know where to start...

Thank you all...

Petros


Solution

  • I would try this in console:

    Categorization.news.first.exhibit.foto    
    

    See if this won't give you the needed Image object. The thing is that news have several possible exhibits.