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

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

型号代码:

class Post  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 

有人指导我存档这个。 提前致谢。

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

呼叫

 super(upload) 

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

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

我找到了解决方案。 在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