图像名称未插入到轨道上的ruby中的数据库中

时间:2013-10-29 17:38:57

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

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

型号代码:

 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

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

3 个答案:

答案 0 :(得分:0)

那是因为你的保存助手与ActiveRecord保存冲突,你甚至没有保存在该方法中做任何事情。

致电

super(upload) 
保存方法中的

(应该是第一行)

答案 1 :(得分:0)

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

答案 2 :(得分: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