0

我有一个 Rails 4 应用程序,并且刚刚安装了 Paperclip gem 来处理图像上传。我无法让它工作,在我上传照片后它只是说丢失。有人知道出了什么问题吗?

~settings/_form.html.erb

>     <%= form_for(@setting, :html => { :multipart => true }) do |f| %>
>       <% if @setting.errors.any? %>
>         <div id="error_explanation">
>           <h2><%= pluralize(@setting.errors.count, "error") %> prohibited this setting from being saved:</h2>
>     
>           <ul>
>           <% @setting.errors.full_messages.each do |msg| %>
>             <li><%= msg %></li>
>           <% end %>
>           </ul>
>         </div>
>       <% end %>
>     
>       <div class="field">
>         <%= f.label :title %><br>
>         <%= f.text_field :title %>
>       </div>
>       <div class="field">
>         <%= f.label :description %><br>
>         <%= f.text_area :description %>
>       </div>
>       <div class="field">
>         <%= f.label :paragraph %><br>
>         <%= f.text_area :paragraph %>
>       </div>
>        <div>
>       <%= f.file_field :photo %>
>       </div>
>       <div class="actions">
>         <%= f.submit %>
>       </div>
>     <% end %>

我的设置模型~setting.rb

class Setting < ActiveRecord::Base
    attr_accessible :title, :description, :paragraph

    has_attached_file :photo
end

照片迁移

class AddAttachmentPhotoToSettings < ActiveRecord::Migration
  def self.up
    change_table :settings do |t|
      t.attachment :photo
    end
  end

  def self.down
    drop_attached_file :settings, :photo
  end
end

设置迁移

class CreateSettings < ActiveRecord::Migration
  def change
    create_table :settings do |t|
      t.string :title
      t.text :description
      t.text :paragraph

      t.timestamps
    end
  end
end

~settings/Show.html.erb

<p id="notice"><%= notice %></p>
<p> <%= image_tag @setting.photo.url %> </p> <br />
<p>
  <strong>Title:</strong>
  <%= @setting.title %>
</p>

<p>
  <strong>Description:</strong>
  <%= @setting.description %>
</p>

<p>
  <strong>Paragraph:</strong>
  <%= @setting.paragraph %>
</p>

<%= link_to 'Edit', edit_setting_path(@setting) %> |
<%= link_to 'Back', settings_path %>

无法弄清楚出了什么问题。上传的照片没有显示它只是说“失踪”。将不胜感激一些帮助!:)

4

2 回答 2

1

你可以保留第一个:setting_params。这似乎是您的控制器中确保强大参数的一种方法(请参阅: http: //guides.rubyonrails.org/getting_started.html#saving-data-in-the-controller)。

要解决它,请在此方法中添加关系,如下所示:

private
  def setting_params
    params.require(:post).permit(:title, :description, :paragraph, :photo)
  end
于 2013-09-11T13:29:41.390 回答
0

我很高兴告诉所有遇到或将遇到与我刚刚发现的相同问题的人!

默认情况下,您生成的控制器要添加 :photo 属性来定义“创建”,如下所示:

def create
    @setting = Setting.new(setting_params)
end

只需将其更改为:

def create
    @setting = Setting.create(params[:setting])
end

(为了清楚起见;将设置更改为您自己的脚手架名称。)

于 2013-09-11T13:00:46.790 回答