I can't wrap my head around trying to find the number of posts inside
each category. I believe you would use a join for this, or some sort
of association.
The "models/category.rb":
class Category < ActiveRecord::Base
has_and_belongs_to_many :posts
end
The "models/post.rb"
class Post < ActiveRecord::Base
has_many :comments
belongs_to :category
end
How would I do something like this? I assume you would query it like:
@category = Category.find(:all)
@category.post.size
I can't wrap my head around trying to find the number of posts inside
each category. I believe you would use a join for this, or some sort
of association.
The "models/category.rb":
class Category < ActiveRecord::Base
has_and_belongs_to_many :posts
end
The "models/post.rb"
class Post < ActiveRecord::Base
has_many :comments
belongs_to :category
end
How would I do something like this? I assume you would query it like:
class Category < ActiveRecord::Base
has_and_belongs_to_many :posts
end
The "models/post.rb"
class Post < ActiveRecord::Base
has_many :comments
belongs_to :category
Both sides of a habtm are always habtm:
has_and_belongs_to_many :categories
end
How would I do something like this? I assume you would query it like:
No @ - there's no reason to make categories into an instance variable.
categories = Category.find(:all)
categories.each do |cat|
p cat.posts.count
end
Think of cat.posts as simultaneously an array of all posts, and a super-model that can do anything Post can (such as Post.find()) but with the link to the Category automatically turned on.