0

在我使用 gem“Paperclip”之前,我正在尝试将没有 gem 的图像上传到一个名为“Course Classifications”的模型。Rails 版本是Rails 3.0.10

当我尝试创建“课程分类”时,出现以下错误: undefined method `name 'for nil: NilClass

我想它一定与我要上传的图像有关,因为当我不加载图像时,模型会正常创建。

根据我的控制台,错误出现在方法' create''if @course_clasification.save'的行中

可以是什么?

“看跌期权”向我抛出以下内容:

"PARAMS: {\"name\"=>\"Prueba12312\", \"description\"=>\"\", \"status\"=>\"1\", \"picture\"=>#<ActionDispatch::Http::UploadedFile:0x0055ffb16c36d8 @original_filename=\"Selección_250.png\", @content_type=\"image/png\", @headers=\"Content-Disposition: form-data; name=\\\"course_clasification[picture]\\\"; filename=\\\"Selecci\\xC3\\xB3n_250.png\\\"\\r\\nContent-Type: image/png\\r\\n\", @tempfile=#<Tempfile:/tmp/RackMultipart20210722-21412-xnr47e>>}"
"NAME: Prueba12312"

我的代码如下:

控制器:

     def create
        @course_clasification = CourseClasification.new(params[:course_clasification])
        p "PARAMS: #{params[:course_clasification]}"
        if params[:course_clasification].present?
          file = params[:course_clasification][:picture]
          File.open(Rails.root.join('public','uploads', file.original_filename), 'wb') do |f|
            f.write(file.read)
          end
        end
        respond_to do |format|
          if @course_clasification.save
            format.html { redirect_to(course_clasifications_path, :notice => 'Classification was created') }
            format.xml  { render :xml => @course_clasification, :status => :created, :location => @course_clasification }
          else
            format.html { render :action => "new" }
            format.xml  { render :xml => @course_clasification.errors, :status => :unprocessable_entity }
          end
        end
      end

  def upload
    uploaded_io = params.require(:course_clasification).permit(:picture)
    File.open(Rails.root.join('public','uploads',uploaded_io.original_filename), 'wb') do |file|
      file.write(uploaded_io.read)
    end
  end

模型:

class CourseClasification < ActiveRecord::Base
    has_many :courses
    has_many :enrollments

  validates :name, presence: true
=begin
    has_attached_file :avatar
    # Validate content type
    validates_attachment_content_type :avatar, content_type: /\Aimage/
    # Validate filename
    validates_attachment_file_name :avatar, matches: [/png\Z/, /jpe?g\Z/]
    # Explicitly do not validate
    do_not_validate_attachment_file_type :avatar
=end
    scope :actives, -> { where('status = 1') }
    scope :inactives, -> { where('status = 0') }


end

形式:

<%= form_for(@course_clasification, html: { style: "flex-direction: column; width: 50%;", :multipart => true }) do |f| %>
  <div class="actions">
    <%= link_to '<i class="fa fa-chevron-circle-left" aria-hidden="true"></i> Regresar'.html_safe, course_clasifications_path, class: "btn-button button--indigo" %>
    <%= f.submit(("&#xf0c7; " + t('action.save')).html_safe, :alt => "Guardar", :title => "Guardar", :class => "button__submit btn-button button--green", :style => "font-family: FontAwesome, verdana, sans-serif; float: right; margin-top: 0; margin-right: 7px;") %>
  </div>

  <% lang = current_user.localization.languaje %>
  <% if @course_clasification.errors.any? %>
    <div id="error_explanation">
      <h2><%= t('activerecord.errors.template.header', count: @course_clasification.errors.size, model: t('activerecord.models.course_clasification')) %>:</h2>
      <p>
        <%= t('activerecord.errors.template.body') %>
      </p>
      <ul>
      <% @course_clasification.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field field-full" style="margin-top: 40px;">
    <%= f.label t('str_name_areas_'+ lang) %><br />
    <%= f.text_field :name %>
  </div>

  <div class="field field-full">
    <%= f.label "Agregar imágen a player" %><br />
    <%= f.file_field :picture %>
    <%# if @course_clasification.avatar? %>
      <%# image_tag @course_clasification.avatar.url(:thumb) %>
    <%# end %>
  </div>

<% end %>

架构:

class CreateCourseClasification < ActiveRecord::Migration
  def self.up
    create_table :course_clasifications do |t|
      t.string :name
      t.text :description
      t.boolean :status
      t.string :picture

      t.timestamps
    end
  end

end
4

1 回答 1

0

我看到的一个问题是您没有使用Strong Parameters。这意味着

@course_clasification = CourseClasification.new(params[:course_clasification])

基本上会尝试创建一个空对象,因为没有参数被列入白名单(Rails 基本上省略了没有列入白名单的内容),因此 ActiveRecord 对象无效并且保存失败。将其更改为类似

def course_classification_params
    # make sure to list all the save params!
    params.permit(:name, :description, :status, ...)
end

@course_clasification = CourseClasification.new(course_classification_params[:course_clasification])

于 2021-07-22T19:59:01.933 回答