【问题标题】:How do I get my image upload to work on rails?如何让我的图像上传在 Rails 上工作?
【发布时间】: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


    【解决方案1】:

    您的:picture 不在您的picture_params允许。允许它保存在 DB

    def picture_params
       params.require(:picture).permit(:artist, :title, :url, :picture)
    end
    

    【讨论】:

    • @icecreamrabbit 你的意思是在迁移中?
    • 是的,我假设当您说 DB 时,您的意思是我的架构,对吗?
    • 并非如此。我的意思是数据库。但是,您还需要添加架构,数据类型可以是 blob
    • 抱歉,它不起作用,你能快速引导我完成这两个步骤吗?迁移无法正常工作,我不确定您所说的数据库是什么意思。谢谢!!
    【解决方案2】:

    试试回形针宝石。本教程也很有帮助。 https://richonrails.com/articles/getting-started-with-paperclip

    【讨论】:

      猜你喜欢
      • 2020-09-14
      • 1970-01-01
      • 1970-01-01
      • 2013-02-24
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多