Reputation: 587
I am trying to model a relationship between Image model and Page model with the following constraints:
1 - a page can have a maximum of one image ( 0 image is also acceptable )
2 - an image is can appear in many pages.
so the relationship could be surmised as following:
class Image < ActiveRecord :: Base
has_many :pages, :through :imageables
end
class Page < ActiveRecord :: Base
has_one :image, :through :imageables
end
class Imageable < ActiveRecord :: Base
belongs_to :image
belongs_to :page
end
Usually this associations either exist with both classes Image and Page with has_many :through or both having has_one :through Is it possible to mix between has_one :through and has_many :through in this case ? ActiveRecord does not mention this particular case
P.S: I chose to use the join model way since i have other models that could have the same images as well with different constraints (has_many instead of has_one)
Thanks for your help!
Upvotes: 1
Views: 865
Reputation: 587
The code above didn't work... And i found a median solution to implement the schema that i needed.
The final code looks like :
class Image < ActiveRecord :: Base
has_many :pages, :through :imageables
end
class Page < ActiveRecord :: Base
has_many :image, :through :imageables
accepts_nested_attributes :images, allow_destroy => true
end
class Imageable < ActiveRecord :: Base
belongs_to :image
belongs_to :page
validates_uniqueness_of :page_id
end
When i use rails_admin to edit my models, i get just the thing when it comes to add a new image and the validation in Imageable ensure the ditor do not mess around with the specifications...
It is little bit weird as a solution, but believe me, it is well adapted for the context of the app that i am developping...
I am posting it so if somebody had similar concern.
Upvotes: 1