Reputation: 3
Here is my controller
class ArticlesController < ApplicationController
def new
@article=Article.new
end
def index
@articles = Article.all
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render 'new'
end
end
def show
@article = Article.find(params[:id])
end
def edit
@article = Article.find(params[:id])
end
def update
@article = Article.find(params[:id])
if @article.update(article_params)
redirect_to @article
else
render 'edit'
end
end
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to articles_path
end
private
def article_params
params.require(:article).permit(:title, :text)
end
end
Here's my form
<%= form_for @article, :html => { :multipart => true } do |f| %>
<% if @article.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@article.errors.count, "error") %> prohibited this article from being saved:</h2>
<ul>
<% @article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.file_field :photo %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
I am not able to upload the photo infact it does not show any error, but neither anything(path of image) is saved on database nor any photo is saved. I am new on rails, just trying to create a form which have features of uploading photo.
class Article < ActiveRecord::Base
validates :title, presence: true, length: { minimum: 5 }
has_attached_file :photo
validates_attachment :photo, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png"] }
end
I have tried almost every tutorial and also found some of the Similar Problem but it seems nothing has resolved the issue. Please help me out.
Upvotes: 0
Views: 381
Reputation:
You need to add photo
to your strong params:
def article_params
params.require(:article).permit(:title, :text, :photo)
end
Without it the value is not passed over to the model to be validated and saved.
I am assuming you already ran the migration to add Paperclip's photo_file_name
, photo_file_size
, photo_content_type
, photo_updated_at
fields to your articles
table.
Note: It is only necessary to include the attached file name photo
in the strong parameters; as long as this value reaches the model Paperclip will handle the rest.
In addition, you need to disable Paperclip's spoofing validation. It uses the OS file
command the determine the MIME type of the file but Windows doesn't have a file command so it always fails. You can disable the spoofing check by putting something like this in an initializer:
module Paperclip
class MediaTypeSpoofDetector
def spoofed?
false
end
end
end
Upvotes: 1