I'm trying to setup a basic form with the ability to upload a picture, a title and a body of text. I'm using the paperclip 4.2.1
gem and rails 4.2.0
.
The form shows up fine, I'm able to type in a title, some body text and select a picture. However, when I submit the form, it skips the show method and goes back to the index page and the image does not get uploaded to the database.
When I submit the form with only the title and body text, it does display in the show method. I did verify the source code of the form page shows "enctype="multipart/form-data". Does anyone know what im missing??
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
end
Model --> article.rb
class Article < ActiveRecord::Base
has_attached_file :image
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
end
View --> 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 %>
view -> 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>
view -> 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 %>
Controller --> 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
I'm very new to ruby and programming in general, so it's probably some type somewhere but I've been searching for days and I'm not sure why the picture wont upload.
You have a typical validation error in create
method. Just change Article.create
to Article.create!
and you will see error and backtrace. It will help you to investigate and fix problem.