【发布时间】:2015-03-10 18:47:30
【问题描述】:
我正在尝试设置一个能够上传图片、标题和正文的基本表单。我正在使用paperclip 4.2.1 gem 和rails 4.2.0。
表格显示得很好,我可以输入标题、一些正文并选择图片。但是,当我提交表单时,它会跳过 show 方法并返回到索引页面,并且图像不会上传到数据库。
当我提交只有标题和正文的表单时,它会显示在 show 方法中。我确实验证了表单页面的源代码显示“enctype="multipart/form-data"。有人知道我缺少什么吗??
schema.rb
ActiveRecord::Schema.define(version: 20150310181944) do
create_table "articles", force: :cascade do |t|
t.string "title"
t.text "text"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "image_file_name"
t.string "image_content_type"
t.integer "image_file_size"
t.datetime "image_updated_at"
end
结束
模型 --> article.rb
class Article < ActiveRecord::Base
has_attached_file :image
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
end
查看 --> new.html.erb
新文章
<%= form_for @article, html: { multipart: true } do |f| %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.label :image %>
<%= f.file_field :image %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
<%= link_to 'Back', articles_path %>
查看-> index.html.erb
<h1>Listing articles</h1>
<%= link_to 'New article', new_article_path %>
<table>
<tr>
<th>Title</th>
<th>Text</th>
<th>Image</th>
</tr>
<% @articles.each do |article| %>
<tr>
<td><%= article.title %></td>
<td><%= article.text %></td>
<td><%= image_tag article.image.url %></td>
</tr>
<% end %>
</table>
查看 -> show.html.erb
<p>
<strong>Title:</strong>
<%= @article.title %>
</p>
<p>
<strong>Text:</strong>
<%= @article.text %>
</p>
<p>
<%= image_tag @article.image.url %>
</p>
<%= link_to 'Back', articles_path %>
控制器 -->articles_controller.rb
class ArticlesController < ApplicationController
def index
@articles = Article.all
end
def show
@article = Article.find(params[:id])
end
def new
@article = Article.new
end
def create
@article = Article.create(article_params)
@article.save
redirect_to @article
end
private
def article_params
params.require(:article).permit(:title, :text, :image)
end
end
总的来说,我对 ruby 和编程非常陌生,所以它可能是某个地方的某种类型,但我已经搜索了好几天,我不确定为什么图片不会上传。
【问题讨论】:
-
你能用'show'方法打印一些东西吗,你能把你在控制器的'show'方法中得到的参数贴出来
标签: ruby-on-rails paperclip multipart form-for