Reputation: 2280
I have Advertisements which can have ladyies, but only if the type is a "club".
Is there a rails-way to do that? especially with not creating lady objects? Do I have to check a lady object, before creating, if her parent is type=club?
class Advertisement < ActiveRecord::Base
validates_inclusion_of :type, in: %w(club lady)
has_many :ladies, :dependent=>:destroy
#only have ladies if the club =
def ladies
return nil unless type == "club"
super
end
end
I'm using Rails 3.2.
Upvotes: 3
Views: 2868
Reputation: 3700
It seems all this is mixing composition (has_many) with inheritance (lady < advertisement) which doesn't make much sense (technically and conceptually). If this is the case and you are not using Lady and Club objects, you should at least rename the type to ad_type...
Assuming you're making a self referential join you'll then need a club_id column :
class Advertisement < ActiveRecord::Base
has_many :ladies, -> {where(type: 'club')}, class_name: "Advertisment"
end
Upvotes: 0
Reputation: 38418
Perhaps using active record association extensions: (using proxy_association.owner)
http://guides.rubyonrails.org/association_basics.html#association-extensions
module LadiesAtClub
def at_club
# you may need to iterate over an array or something here...
proxy_association.owner.type == 'club'
end
end
class Advertisement < ActiveRecord::Base
has_many :ladies :extend => LadiesAtClub
end
Upvotes: 0
Reputation: 4496
The Rails way to do that is STI:
class Advertisement < ActiveRecord::Base
end
class LadyAd < Advertisement
has_many :ladies, :dependent=>:destroy
end
And only LadyAd object able to have ladies.
Upvotes: 3