2013-08-21 106 views
0

我是相當新的Rails和我正在創建一個博客網站,我需要一個職位有一個類別(S)和最終結果URL將是這樣的 - foo.com/category(標題)/發佈(標題)等谷歌搜索後,然後看這個railscast http://railscasts.com/episodes/47-two-many-to-many。我有以下模型,但不知道路線應該是什麼。Rails路由通過關聯

我現在應該使用類別的索引視圖來顯示所有帖子嗎?

模式 - 的歸類

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

模式 - 分類

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

型號 - 發佈

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 

回答

2
resources :categories do 
    resources :posts 
end 

會給你的資源/分類/ 1 /後/ 1

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

已經在ULR看看這個railscast爲標題

編輯:

爲了回答你以往的評論,我建議你: @Category = Category.find(PARAMS [ :id]) @posts = @ category.posts

+0

好的,我需要在我的分類索引控制器中顯示該分類的所有帖子?我認爲這但它不正確@posts = categories.posts –

+0

您是否找到解決方案? – Pierre

+0

沒有:(我發現這[問題](http://stackoverflow.com/questions/5827939/rails-restful-urls-all-posts-under-certain-category)這是我想要的,但我完全失去了創建控制器和視圖作爲正常的rails方式將通過過濾,所以URL會顯示像foo.com/?category=2這樣的東西,但這對用戶或谷歌來說並不好。你能指出我在任何方向還是任何方向你推薦的資源? –