【问题标题】:Ruby on rails - model missing required attr_accessor for [RAILS]Ruby on rails - 模型缺少 [RAILS] 所需的 attr_accessor
【发布时间】:2013-11-25 16:46:12
【问题描述】:

我在 Rails 上使用 ruby​​,但我遇到了一些问题!

我试图创建一个数据库,但它似乎不起作用! 由于命令,我生成了一个模型和一个数据库文件:

rails g model photos 

这里是我的代码

photos_controller.rb:

class PhotosController < ApplicationController


  # POST /photos
  # POST /photos.json
  def create
    @photo = Photo.new(photo_params)


photo_controller.rb

    respond_to do |format|
      if @photo.save
        format.html { redirect_to @photo, notice: 'Photo was successfully created.' }
        format.json { render action: 'show', status: :created, location: @photo }
      else
        format.html { render action: 'new' }
        format.json { render json: @photo.errors, status: :unprocessable_entity }
      end
    end
  end

# Never trust parameters from the scary internet, only allow the white list through.
    def photo_params
      params.require(:photo).permit(:image)
    end
end

在模型 photo.rb 中:

class Photo < ActiveRecord::Base
    has_attached_file :image
end

在文件 2011234116731_create_photos.rb 中:

class CreatePhotos < ActiveRecord::Migration

     def self.up
         add_column :photos, :image_file_name, :string
         add_column :photos, :image_content_type, :string
         add_column :photos, :image_file_size, :string
         add_column :photos, :image_update_at, :string
     end

     def self.down
         remove_column :photos, :image_file_name, :string
         remove_column :photos, :image_content_type, :string
         remove_column :photos, :image_file_size, :string
         remove_column :photos, :image_update_at, :string
     end

end

但是当我尝试加载使用模型元素“图像”的页面时,出现以下错误:

照片模型缺少“image_file_name”所需的 attr_accessor 提取的源代码(第 27 行附近):

POST /photos.json

定义创建 @photo = Photo.new(photo_params) respond_to 做 |格式| 如果@photo.save

我注意到迁移似乎不起作用,因为在我的 scheme.rb 中: (我已经完成了 rake db:migrate 命令)

ActiveRecord::Schema.define(version: 20131124183207) do

  create_table "photos", force: true do |t|
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end

【问题讨论】:

    标签: html ruby-on-rails ruby web


    【解决方案1】:

    迁移似乎没有正确运行。而且它看起来也不像是由rails g model 命令生成的迁移。它缺少create_table 方法。看起来您之前创建了 Photo 模型,然后创建了另一个迁移以添加图像字段。

    我的第一个预感是尝试回滚迁移:

    rake db:migrate:down VERSION=2011234116731
    

    然后再次运行rake db:migrate 并检查您的架构文件以确保所有列都在那里。

    【讨论】:

    • 非常感谢!现在完美了!
    猜你喜欢
    • 1970-01-01
    • 2016-01-03
    • 1970-01-01
    • 2011-07-03
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    相关资源
    最近更新 更多