Dan Mitchell
Dan Mitchell

Reputation: 864

Rails route for through association

I am fairly new to Rails and I am creating a blog site and I need a post to have a category(s) and the end result url will be something like this - foo.com/category(title)/post(title) so after alot of Googling and then watching this railscast http://railscasts.com/episodes/47-two-many-to-many. I have the following models but have no idea what the routes should be.

Should I now be using the index view of category to display all posts?

Model - Categorisations

class Categorisations < ActiveRecord::Base
  attr_accessible :category_id, :product_id
end

Model - Category

class Category < ActiveRecord::Base
  attr_accessible :title, :image
  has_many :categorisations
  has_many :posts, :through => :categorisations
end

Model - Post

class Post < ActiveRecord::Base
attr_accessible :body, :is_verified, :publish_date, :title, :url, :tag_list, :image, :category_id
  has_many :categorisations
  has_many :categories, :through => :categorisations
end

Upvotes: 0

Views: 1755

Answers (1)

Pierre
Pierre

Reputation: 1114

resources :categories do
  resources :posts
end

Will give you the resources for /category/1/post/1

http://guides.rubyonrails.org/routing.html#nested-resources

Have a look at this railscast for titles in the ulr

EDIT:

To answer your previous comment i would suggest you this: @category = Category.find(params[:id]) @posts = @category.posts

Upvotes: 3

Related Questions