【问题标题】:Image name not inserted into database in ruby on rails图像名称未在 ruby​​ on rails 中插入数据库
【发布时间】:2013-11-09 00:45:22
【问题描述】:

我在将图像名称存储到数据库时遇到问题。图片上传到文件夹工作正常,但图片名称不会保存到数据库中

型号代码:

 class Post < ActiveRecord::Base
   attr_accessible :name, :imag
   attr_accessor :imag

  def self.save(upload)
    name = upload['imag'].original_filename
    directory = 'public/data'
    # render :text => directory
    # create the file path
    path = File.join(directory,name)
    # write the file
    File.open(path, "wb") { |f| f.write(upload['imag'].read)}
  end

end

控制器代码:

  def create
    @a=params[:post][:imag].original_filename  /* how to pass in this image name into params[:post] */
    pos= Post.save(params[:post])
    if pos
      redirect_to :action =>"index"
    else
      redirect_to :action =>"posts"
    end
  end

任何人都指导我存档这个。提前致谢。

【问题讨论】:

    标签: ruby-on-rails ruby image sqlite rails-activerecord


    【解决方案1】:

    那是因为您的保存助手与 ActiveRecord 保存冲突,您甚至没有保存在该方法中执行的任何操作。

    打电话

    super(upload) 
    

    在你的保存方法中(应该是第一行)

    【讨论】:

    • 我找到了下面发布的解决方案。感谢您的支持。
    【解决方案2】:

    您正在使用自定义 self.save 类方法覆盖 ActiveRecord 保存方法。另外,我建议使用回形针之类的上传 gem 或类似的东西

    【讨论】:

    • 我已经使用了回形针 gem,但是在使用 rails 4.0.0 的模型中会出现以下错误。错误:attr_accessible` 被从 Rails 中提取到 gem 中。
    • 该评论毫无意义。您已经用自己的方法覆盖了默认的 ActiveRecord 保存方法。您的方法不会向数据库写入任何内容。这就是为什么您没有将任何信息插入数据库的原因,因为您没有在自定义保存方法中插入它
    • 我找到了下面发布的解决方案。感谢您的支持。
    【解决方案3】:

    我找到了解决方案。 Post.create函数中手动添加图片原文件名。

    控制器代码:

     def create
                Post.super(params[:post])
                pos= Post.create(:name=>params[:post][:name],:image=>params[:post][:image].original_filename) /* here is added image value from uploaded input */
                if pos
                  redirect_to :action =>"index"
                else
                  redirect_to :action =>"posts"
                end
    
              end
    

    型号代码:

    class Post < ActiveRecord::Base
       attr_accessible :name, :image
    
      #attr_accessor :imag
      def self.super(upload)
        name = upload['image'].original_filename
        directory = 'public/data'
       # render :text => directory
        # create the file path
        path = File.join(directory,name)
        # write the file
        File.open(path, "wb") { |f| f.write(upload['image'].read)}
      end
    
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多