Ruby on rails ruby on rails中未将图像名称插入数据库
我无法将图像名称存储到数据库中。图像上载到文件夹工作正常,但图像名称不会保存到数据库中 型号代码:Ruby on rails ruby on rails中未将图像名称插入数据库,ruby-on-rails,ruby,image,sqlite,rails-activerecord,Ruby On Rails,Ruby,Image,Sqlite,Rails Activerecord,我无法将图像名称存储到数据库中。图像上载到文件夹工作正常,但图像名称不会保存到数据库中 型号代码: class Post < ActiveRecord::Base attr_accessible :name, :imag attr_accessor :imag def self.save(upload) name = upload['imag'].original_filename directory = 'public/data' # rend
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
有人指导我把这个存档。提前感谢。这是因为您的保存帮助程序与ActiveRecord保存冲突,并且您甚至没有使用该方法进行任何保存操作 召唤
在save方法中(应该是第一行)您正在使用自定义的
self.save
类方法覆盖ActiveRecord保存方法。另外,我建议使用像回形针之类的上传宝石或类似的东西,我已经找到了解决方案。在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
class Postdirectory
#创建文件路径
path=File.join(目录、名称)
#写文件
File.open(路径,“wb”){| f | f.write(上传['image'].read)}
结束
结束
我已经使用过回形针gem,但在使用rails 4.0.0的im型号中会出现以下错误。错误:attr_accessible`是从Rails提取到gem中的。该注释毫无意义。您已经用自己的方法覆盖了默认的ActiveRecord保存方法。您的方法不会向数据库写入任何内容。这就是为什么你没有在数据库中插入任何信息,因为你没有在你的自定义保存方法中插入信息。我发现下面发布了解决方案。谢谢你的支持。我发现解决方案发布在下面。谢谢你的支持。
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