尝试使用回形针上传图像时Rails收到错误

时间:2016-12-31 16:31:24

标签: ruby-on-rails ruby paperclip

我只是开始学习rails并继续遇到我通常通过搜索来解决的错误。我按照http://guides.rubyonrails.org/getting_started.html上的教程完成了它,现在我正在尝试将图像上传到博客文章中。但现在我仍然坚持使用回形针上传图像,这听起来很简单。 我得到的错误如下:

的未定义方法`附件'

以下是我的文件:

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 edit
    @article = Article.find(params[:id])
  end

  def create
    @article = Article.new(article_params)
    #@article = Article.create(article_params)

    if @article.save
      redirect_to @article
    else
      render 'new'
    end
  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, :image)
    end
end

article.rb

class Article < ApplicationRecord

 has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
  validates :attachment, :attachment_content_type => { :content_type => ['image/png', 'image/jpg']}

  attr_accessor :image_file_name


has_many :comments, dependent: :destroy


validates :title, presence: true,
                    length: { minimum: 2 }


end

_form.html.erb

<%= 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.label :image %><br>
    <%= f.file_field :image %>
  </p>


<p>
  <%= f.submit %>
</p>

<% end %>

2 个答案:

答案 0 :(得分:1)

article.rb模型中,只需将:attachment更改为:image,如:

validates :image, :attachment_content_type => { :content_type => ['image/png', 'image/jpg']}

答案 1 :(得分:0)

在您的文章模型中,您有

validates :attachment, :attachment_content_type => { :content_type => ['image/png', 'image/jpg']}

所以它希望验证“附件”,而不是“图像”。将验证行更改为此

validates :image, :attachment_content_type => { :content_type => ['image/png', 'image/jpg']}

它应该有用。