【问题标题】:Rails: pictures not uploading?Rails:图片无法上传?
【发布时间】:2012-10-01 19:00:47
【问题描述】:

我正在开发我的第一个 Rails 项目,并尝试使用 file_field 上传 photosbelongs_to :album。该表单出现在我的相册/show.html.erb 页面上,因为我想显示相册并让用户能够从一个地方上传图片。但是,当我在表单上按提交时,它似乎没有上传。

这是我的照片/_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 实例是否正在接收我上传的图片,但它总是返回“no”

<% 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

如果您需要任何其他文件,请告诉我

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    你会需要的,

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

    另外,我假设您的上传机制是正确的。 :)

    祝你好运

    【讨论】:

      猜你喜欢
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      • 2019-05-31
      • 2020-11-27
      • 2023-03-16
      • 2020-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多