我有一个 UploadsController 和 UsersController 其中 用户'has_many :uploads' 通过 uploads.rb 中的多态附件。
现在当我导航到 http://localhost:3000/users/1/uploads
我被重新路由到上传#索引并多次调用渲染如下图所示:
Started GET "/users/1/uploads" for 127.0.0.1 at 2011-05-06 22:00:38 +0100
Processing by UploadsController#index as HTML
Parameters: {"user_id"=>"1"}
[1m [35mUser Load (0.0ms) [0m SELECT "users".* FROM "users" WHERE
"users"."id" = 1 LIMIT 1
[1m [36mUpload Load (0.0ms) [0m [1mSELECT "uploads".* FROM
"uploads" [0m
Rendered uploads/_upload.html.erb (0.0ms)
Rendered uploads/_upload.html.erb (0.0ms)
Rendered uploads/_upload.html.erb (0.0ms)
Rendered uploads/index.html.erb within layouts/application
这是我的配置/路由
Uploader::Application.routes.draw do
devise_for :users
resources :users do
resources :uploads
end
root :to => 'users#index'
class UsersController < ApplicationController
def show
@user = User.find
end
views/users/show.html.erb
<div>
<% @user.email %>
<h3 id="photos_count"><%= pluralize(@user.uploads.size, "Photo")%></h3>
<div id="uploads">
<%= image_tag @user.uploads.url(:small)%>
<em>on <%= @user.upload.created_at.strftime('%b %d, %Y at %H:%M') %></em>
</div>
<h3>Upload a Photo</h3>
<%= render "upload/form", :parent => @user, :upload => user.uploads.new %>
class UploadsController < ApplicationController
def index
@uploads = Upload.all
@upload = Upload.new
end
def show
@upload = @parent.uploads.find(params[:id])
@total_uploads = @parent.uploads.find(:all, :conditions =>{ :user_id => @upload.user.id})
end
def create
@upload = @parent.uploads.build(params[:upload])
@upload.document_content_type = MIME::Types.type_for(@upload.document.original_filename).to_s
@upload.document = params[:upload]
if @upload.save
flash[:notice] = "sucessfully saved upload"
respond_with{redirect_to [@parent, :uploads]}
respond_with{ render :json => {:upload => polymorphic_upload_path(@parent)} }
else
render :action => 'new'
end
end
views/uploads/index.html.erb
<% unless @uploads.blank? %>
<% @uploads.each do |upload| %>
<%= render :partial => 'upload', :locals => {:collection =>
@upload.try(:document)} %>
<% end %>
<% end %>
<div id="uploads">
<h3>Upload a document</h3>
<%= render 'form', :parent => @parent, :upload => @upload.new %
</div>
编辑:
Also i have tried to fix this double render error by modifying the create action call to render or redirect without success. This is an excerpt from the log.
Render and/or redirect were called multiple times in this action
controllers/uploads_controller.rb:37:in `create'
谢谢
一切看起来都按预期工作。您看到多个渲染的原因是因为它多次渲染部分"uploads/_upload.html.erb",每个用户上传一个。
您希望 http://localhost:3000/users/1/uploads 重定向到哪里?就像现在一样,您已经说过用户有很多上传,因此此 url 映射到属于 id 为 1 的用户的上传,即 UploadsController 的索引操作。
嵌套资源类似于作用域中的资源。在这种情况下,您的上传范围将限定为其所属的用户。