2

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

型号代码:

 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

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

4

3 回答 3

0

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

称呼

super(upload) 

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

于 2013-10-29T17:52:26.007 回答
0

我找到了解决方案。在 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
于 2013-10-30T15:13:00.343 回答
0

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

于 2013-10-29T17:55:30.207 回答