2012-10-01 116 views
0

我正在处理我的第一个rails项目,并试图使用file_field来上传photos,即​​。该表单出现在我的相册/ show.html.erb页面上,因为我想显示相册并让用户能够从一个地方上传图片。但是,当我按下表单上的提交时,它似乎无法上传。Rails:图片无法上传?

,这里是我的照片/ _form.html.erb

<%= form_for(@photo, :html => { :multipart => true }, :url => { :action => 'create'}) do |f| %> 

<%= f.label :avatar %> 
<%= f.file_field :avatar %> 

<%= f.submit %> 


<% end %> 

这是我的专辑/ show.html.erb页。我加入了if/else语句只是为了测试是否@album实例正在接受我上传的图片,但它始终以“没有”

<% if @album.photos.any? %> 
yes 
<% else %> 
no 
<% end %> 


<div> 
    <%= render 'photos/form' %> 
</div> 

照片控制器回来(我真的很困惑,怎么设置这个实例变量)

class PhotosController < ApplicationController 


def create 
    @album = Album.find(params[:user_id][:album_id]) 
    @photo = @album.build(params[:photo]) 
    respond_to do |format| 
    if @album.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 

相册样板

class Album < ActiveRecord::Base 
    attr_accessible :avatar, :name, :description 
    has_many :user_albums 
    has_many :users, :through => :user_albums 
    has_many :photos 
end 

照片模式

class Photo < ActiveRecord::Base 
    belongs_to :album 
end 

让我知道如果你需要的任何其他文件

回答

1

您需要,

@album.photos.build(params[:photo]) 

另外,我认为你的上传机制是正确的。 :)

祝你好运