2011-04-14 74 views
0

添加子頁面使用RoR的2.3.8不能在控制器

這是我cities_controller.rb

class CitiesController < ApplicationController 
    def show 
    @city = City.find(params[:id]) 
    ... 
    end 

    def shops 
    ... 
    end 

    def countries 
    ... 
    end 
end 

這裏是我的routes.rb

map.resources :cities, :collection => {:shops => :get, :countries => :get} 

show網址爲每個id是:

http://localhost/cities/1 

我希望有一些內容shopscountries每個相關id,我想:

http://localhost/cities/1/shops 
http://localhost/cities/1/countries 

我不能讓網頁顯示,空碼擺在首位。我做錯了什麼?

謝謝。

回答

4

:collection選項是當你要作用於整個集合 - 所以你的路由將顯示爲:

http://localhost/cities/shops 
http://localhost/cities/countries 

你想要的是

map.resources :cities, :member => {:shops => :get, :countries => :get} 

參考:http://apidock.com/rails/ActionController/Resources/resources

0

商店和國家可能不是控制器中的方法,而是其他模型。你會希望有一個Countries.rbShops.rb

那麼您需要嵌套的資源,如

resources :cities do 
    resources :shops 
end 

,你需要在商店模型belongs_to :city,並在城市模型中的has_many :shops這將讓你訪問城市/ 1/shops ....或類似的東西

然而想一想數據的結構,國家真的屬於城市(嵌套資源意味着什麼),或者國家是否包含城市。你會想要城市belongs_to :country等等......

這有幫助嗎?

+0

是的,我用控制器搜索一些東西,並在視圖中顯示結果,但在模型方面,沒有關聯。數據結構只是一個例子。 :P – Victor 2011-04-14 05:03:28