HABTM timely response
I am looking for an alternative way to check if ActivityType has any relationships as the way I am doing it now is too 开发者_如何学Pythoncostly (activity_type.activities.empty?
).
I thought about creating a new method such as ActivityType#linked_to_activity?
which would do a query on ActivitiesActivityTypes HABTM join table. This is faster than the previously mentioned method but it is still too slow.
Any pointers are appreciated (apart from the usual "HABTM should be replaced by HM:through" non-constructive comment)
Models
class Activity < ActiveRecord::Base
has_and_belongs_to_many :activity_types, :uniq => true
end
class ActivityType < ActiveRecord::Base
has_and_belongs_to_many :activities
end
View
%table
- @activity_types.each do |activity_type|
%tr
%td
- if activity_type.activities.empty?
Do something here...
Attempt at ActivityType#linked_to_activity?
class ActivityType < ActiveRecord::Base
has_and_belongs_to_many :activities
def linked_to_activity?
ActivityType.find_by_sql(["SELECT * FROM activities_activity_types WHERE activity_type_id = ?", id]).empty? ? false : true
end
end
NB:
- Running on Rails v2.3.5
- DB is MySQL with indices on foreign keys
I think you are on the right track. It's a matter of preference, but I usually do it with a count:
class ActivityType < ActiveRecord::Base
has_and_belongs_to_many :activities
def linked_to_activity?
self.activities.count > 0
end
end
Edit:
As the comment below states: Using select count(*)
will only retrieve one line from the DB, while select *
retrieves all (unless of course you add a limit 1
at the end).
Also: I try not to litter my models with plain SQL unless it's absolutely necessary for performance reasons.
This should improve the performance of your #linked_to_activity?
:
class ActivityType < ActiveRecord::Base
has_and_belongs_to_many :activities
def linked_to_activity?
ActivityType.count_by_sql(["SELECT COUNT(*) FROM activities_activity_types WHERE activity_type_id = ?", id]) > 0
end
end
精彩评论