2013-02-08 73 views
0

位置有列表。從位置索引中,我希望用戶能夠添加新的列表(屬於該位置),然後重定向到更新的索引。嵌套路由在創建時失敗

我的路線如下:

match 'listings/search' => 'listings#search' 
resources :locations do 
    resources :listings 
end 
resources :locations 
resources :listings 
match "listings/:location" => 'listings#show' 

下面是上市的形式:

<%= form_for(@listing, :url=>"/locations/#{@location_id}/listings") do |f| %> 
    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

我想這應該調用創建方法listings_controller:

def create 
    @location= Location.find(params[:location_id]) 
    @location_id = @location.id 
    @listing = @location.listings.create(params[:listing]) 

    respond_to do |format| 
    if @listing.save 
     redirect_to location_listings_path(@location_id) 
    else 
     format.html { render action: "new" } 
    end 
    end 
end 

當我按提交時,它重定向到/位置/ 1 /列表 這是確切的我想要什麼。但窗口是空白的。如果我按刷新(任何其他時間訪問位置/ 1 /列表),它會正確顯示索引。

+0

您可以刪除'respond_to'塊(留下內容),但將else改爲「render:new」。 – jvnill

+0

哇。非常感謝。這是從腳手架代碼中遺留下來的,我從不會認爲這是罪魁禍首。它現在正常工作! – tuna

+0

很高興能有所幫助:)祝你好運! – jvnill

回答

1

你也可以改變你的form_for到:

<%= form_for([@location, @listing]) do |f| %> 

所以你不必添加:URL的一部分。

+0

華麗!我一直在想如何做到這一點。 – tuna

0

一些改造完成:

# config/routes.rb 
resources :locations do 
    resources :listings 
    get :search, on: :collection # will be directed to 'locations#search' automatically 
end 

resources :listings 

形式的URL,可以使用這樣或方式彼得建議:

<%= form_for(@listing, url: location_listings_path(@location)) do |f| %> 
    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

而且你的控制器可以被清理,以及:

# app/controllers/listings_controller.rb 
def create 
    @location = Location.find(params[:location_id]) 
    @listing = @location.listings.build(params[:listing]) 

    if @listing.save 
    redirect_to location_listings_path(@location_id) 
    else 
    render action: :new 
    end 
end