【发布时间】:2015-10-04 13:46:09
【问题描述】:
我正在尝试实现图片上传功能(没有 gem),当我在选择照片后按提交时出现此错误:
Ac
tiveRecord::UnknownAttributeError in PicturesController#create
unknown attribute 'picture' for Picture.
Extracted source (around line #13):
def create
# make a new picture with what picture_params returns (which is a method we're calling)
**@picture = Picture.new(picture_params)** << where i'm getting the error
if @picture.save
# if the save for the picture was successful, go to index.html.erb
redirect_to pictures_url
如何设置我的环境以便我的照片保存在数据库中?
控制器:
class PicturesController < ApplicationController
def index
@pictures = Picture.all
end
def new
@picture = Picture.new
end
def create
# make a new picture with what picture_params returns (which is a method we're calling)
@picture = Picture.new(picture_params)
if @picture.save
# if the save for the picture was successful, go to index.html.erb
redirect_to pictures_url
else
# otherwise render the view associated with the action :new (i.e. new.html.erb)
render :new
end
end
def show
@picture = Picture.find(params[:id])
end
def edit
@picture = Picture.find(params[:id])
end
def update
@picture = Picture.find(params[:id])
if @picture.update_attributes(picture_params)
redirect_to "/pictures/#{@picture.id}"
else
render :edit
end
end
def destroy
@picture = Picture.find(params[:id])
@picture.destroy
redirect_to pictures_url
end
private
def picture_params
params.require(:picture).permit(:artist, :title, :url, :picture)
end
end
迁移:
class CreatePictures < ActiveRecord::Migration
def change
create_table :pictures do |t|
t.string :artist
t.string :title
t.string :url
t.string :pictures
t.timestamps null: false
end
end
end
我通过编辑文件手动添加了 t.string :pictures,它仍然以这种方式工作还是我需要运行命令?
我的表格:
<container>
<center>
<%= form_for @picture do |f| %>
<input type="file" multiple> <%= f.file_field :picture %>
<p>Drag your files here or click in this area.</p>
<button type="submit"> <%= f.submit "Save" %> Upload </button>
</form>
<% end %>
</container>
我正在使用简单的拖放上传。 感谢您的帮助,我真的很感激!
【问题讨论】:
-
您已将文件添加到现有迁移。该迁移是否已经推送到生产或 git?如果是这样,您不应该这样做,而是生成一个新的迁移。如果这是一个新的迁移(没有推送到任何地方 - 仅存在于本地),但已经运行,您需要运行
rake db:migrate:redo。正如 Pavan 在回答中提到的,您还希望将此列命名为picture。
标签: ruby-on-rails ruby forms upload