我目前正在做一个上传图片的项目。这些相册中有用户、相册和图片。我已经到了以用户身份创建相册的地步(尚未完成会话、身份验证或登录,但已完成注册)。我在提交 Rails 的表单后收到错误消息
Couldn't find User without an ID
我注意到我的 new.html.erb 的 URL 没问题:
http://localhost:3000/users/13/albums/new
(没问题)
但是在我提交之后,它给了我一个错误,页面是:
http://localhost:3000/albums/58
(问题。url中没有user_id)
有谁知道为什么我的路线突然像那样改变以及如何解决?错误出现在我的 app/controllers/albums_controller.rb:14:in `show' @user = User.find(params[:user_id]) 行。
新的.html.erb
<%= form_for (@album), url: user_albums_path, :html => { :id => "uploadform", :multipart => true } do |f| %>
<div>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :description %>
<%= f.text_area :description %>
<br>
<%=f.submit %>
</div>
<% end %>
专辑控制器
def show
@user = User.find(params[:user_id])
@album = @user.albums.find(params[:id])
@photo = @album.photos.build(params[:photo])
respond_to do |format|
if @user.save
format.html { redirect_to album_photo_path(@album), notice: 'Album was successfully created.' }
format.json { render json: @album, status: :created, location: @album}
else
format.html { render action: "new" }
format.json { render json: @album.errors, status: :unprocessable_entity }
end
end
end
def update
end
def edit
end
def create
@user = User.find(params[:user_id])
@album = @user.albums.build(params[:album])
respond_to do |format|
if @user.save
format.html { redirect_to @album, notice: 'Album was successfully created.' }
format.json { render json: @album, status: :created, location: @album}
else
format.html { render action: "new" }
format.json { render json: @album.errors, status: :unprocessable_entity }
end
end
end
路线
Pholder::Application.routes.draw do
resources :users do
resources :albums
end
resources :albums do
resources :photos
end