地点都有列表。从位置索引中,我希望用户能够添加一个新的列表(属于该位置),然后被重定向到更新的索引。
我的路由如下:
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中的create方法:
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当我按下submit时,它会重定向到/locations/1/listings,这正是我想要的。但是窗口是空的。如果我按refresh (访问位置/1/listings),它会正确地显示索引。
发布于 2013-02-08 17:12:47
您还可以将您的form_for更改为:
<%= form_for([@location, @listing]) do |f| %>因此,您不必添加:url部分。
发布于 2013-02-08 17:17:45
做了一些返工:
# config/routes.rb
resources :locations do
resources :listings
get :search, on: :collection # will be directed to 'locations#search' automatically
end
resources :listings表单url可以像这样使用,也可以按照Peter建议的方式使用:
<%= 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
endhttps://stackoverflow.com/questions/14768927
复制相似问题