【发布时间】:2015-10-03 09:44:15
【问题描述】:
我有一个表单,目前保存上传到我的项目的图像标题、描述和 URL。我在表单中添加了一个上传选项,现在我对它如何准确地保存到我的服务器并在上传后显示感到困惑。另外 - 这不是优先事项 - 还有一种方法可以为我的上传分配一个 url 以便用户可以共享?
我的表单:(f.file_field 图片是我用来上传图片的)
<h1>Add a picture</h1>
<%= link_to "Back to Pictures", pictures_url %>
<%= form_for @picture do |f| %>
<p>
<%= f.label :artist %><br>
<%= f.text_field :artist %>
</p>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.file_field :picture %>
</p>
<p>
<%= f.label :url %><br>
<%= f.text_field :url %>
</p>
<p>
<%= f.submit "Save" %>
</p>
<% end %>
</center>
控制器:
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)
end
end
感谢您的帮助!我想尽可能地减少这种情况,并且不想选择宝石。
【问题讨论】:
标签: ruby-on-rails forms upload server