Hey,
I think this is pretty simple, but I just can’t get my head around it…
I have a forum with the following models
CATEGORIES
id
title
TOPICS
id
title
category_id
user_id
created_on
POSTS
id
message
user_id
topic_id
created_on
I want to be able to display the time when the last POST was posted in
each CATEGORY.
Should i change my database layout, or is there a way to do it with my
current layout?
Thanks for your help guys!
Scott H. wrote:
Hey,
I think this is pretty simple, but I just can’t get my head around it…
I have a forum with the following models
CATEGORIES
id
title
TOPICS
id
title
category_id
user_id
created_on
POSTS
id
message
user_id
topic_id
created_on
I want to be able to display the time when the last POST was posted in
each CATEGORY.
Should i change my database layout, or is there a way to do it with my
current layout?
Thanks for your help guys!
You can do it with your current layout, but it will be expensive. The
best way is to create a cache on your category table. And then set that
cache in an after_create filter on the post model.
class Post
after_create :set_last_post
def set_last_post
topic.category.update_attribute(:last_post_at, Time.now)
end
end
Category.find(1).last_post_at #=> cached datetime
Hi Scott,
or you could use the relationship that is already built in:
@last_post = Category.find(cat_id).posts.find(:first, :order =>
“created_on DESC”)
assuming you set up the relationships and stuff.
I would probably stick that method in the Category model:
class Category
def self.find_last_post(cat_id)
Category.find(cat_id).posts.find(:first, :order => "created_on
DESC")
end
end
then you can do:
@last_sent = Category.find_last_post(cat_id)
I think Alex’s way may be faster.
–jake
Alex W. wrote:
Scott H. wrote:
Hey,
I think this is pretty simple, but I just can’t get my head around it…
I have a forum with the following models
CATEGORIES
id
title
TOPICS
id
title
category_id
user_id
created_on
POSTS
id
message
user_id
topic_id
created_on
I want to be able to display the time when the last POST was posted in
each CATEGORY.
Should i change my database layout, or is there a way to do it with my
current layout?
Thanks for your help guys!
You can do it with your current layout, but it will be expensive. The
best way is to create a cache on your category table. And then set that
cache in an after_create filter on the post model.
class Post
after_create :set_last_post
def set_last_post
topic.category.update_attribute(:last_post_at, Time.now)
end
end
Category.find(1).last_post_at #=> cached datetime
cheers guys.
I’ll give them ago tonight and let you know how it goes!