2014-05-05 50 views
0

这里是我的控制器无法在导轨4上使用回形针连接照片?

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 

这里是我的形式

<%= 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 %> 

我不能上传照片INFACT它不显示任何错误,但是没有任何东西(图像的路径)保存在数据库也没有保存任何照片。我是新手,只是想创建一个具有上传照片功能的表单。

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 

我已经试过几乎所有的教程,并也发现了一些Similar Problem的,但似乎一切都没有解决这个问题。请帮助我。

回答

1

您需要添加photo到你的坚强PARAMS:

def article_params 
    params.require(:article).permit(:title, :text, :photo) 
end 

没有它的价值是不是经过对模型进行验证和保存。

我假设你已经运行迁移增加回形针的photo_file_namephoto_file_sizephoto_content_typephoto_updated_at领域的articles表。

注意:只需在强参数中包含附件名称photo;只要这个值达到模型回形针将处理其余的。

此外,您需要禁用Paperclip的欺骗验证。它使用OS file命令确定文件的MIME类型,但Windows没有文件命令,因此总是失败。你可以通过在初始化程序中加入类似这样的东西来禁用欺骗检查:

module Paperclip 
    class MediaTypeSpoofDetector 
    def spoofed? 
     false 
    end 
    end 
end 
+0

是的我早些时候尝试过,但显示错误,所以我删除了它。错误在ArticlesController#update中显示“Paperclip :: Errors :: MissingRequiredValidatorError”。我也提出过这个错误。在我的模型中添加了“validates_attachment:photo,content_type:{content_type:[”image/jpg“,”image/jpeg“,”image/png“]} ”。但我现在不知道该怎么做。 – Pranav

+0

您是否在模型中的强参数**和** validates_attachment中使用了'photo'?你需要两个;强大的参数将照片传递给模型,并验证附件,因为Paperclip坚持至少验证内容类型或文件名。 –

+0

给我看。我以某种方式删除了Paperclip错误,这真是一个愚蠢的错误。但现在,我正在上传.jpg扩展图像文件。它显示文章页面中的错误为“照片的扩展名与其内容不匹配”。 – Pranav