HABTM query

Hi everyone,

I am just playing with a Blog project at the moment. It has a simple
data model of

Post
has_and_belongs_to_many :categories

Category
has_and_belongs_to_many :posts

And the DB tables to serve the model. It’s all working fine and dandy so
far. I want to add a listing to filter by category - here’s where I’m a
bit stuck on the syntax.

How do I get all the posts that belongs to a certain category? I’m
having problems figuring how to write out the condition.

Any hits/suggestions/answers would be greatly appreciated.

Many thanks,
Dany.

Sorry, forgot to ask one more thing. I have listed the Categories under
the Post, and made each one of the a link to the action
list_by_category. I can’t quite figure out how to pass the value of the
category from the view back to the controller to be used in the query.
This is assuming I need to do this, of course…

Thanks,
Dany.

On 30 Oct 2007, at 07:49, Dany Wu wrote:

Sorry, forgot to ask one more thing. I have listed the Categories
under
the Post, and made each one of the a link to the action
list_by_category. I can’t quite figure out how to pass the value of
the
category from the view back to the controller to be used in the query.
This is assuming I need to do this, of course…

You need to pass the id of the category

You can then do (in your list_by_category action) @posts =
Category.find(params[:id]).posts.

Frederick C. wrote:

On 30 Oct 2007, at 07:49, Dany Wu wrote:

Sorry, forgot to ask one more thing. I have listed the Categories
under
the Post, and made each one of the a link to the action
list_by_category. I can’t quite figure out how to pass the value of
the
category from the view back to the controller to be used in the query.
This is assuming I need to do this, of course…

You need to pass the id of the category

You can then do (in your list_by_category action) @posts =
Category.find(params[:id]).posts.

Perfect! Thanks for that - I’ve just figured out custom pagination, and
it’s all go!

D.