问题
I have a problem to store image name into database. image upload to folder working fine but image name will not saved into db
Model code :
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
Controller code:
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
Anyone guide me to archive this one. Thanks in advance.
回答1:
that's because your save helper conflicts with the ActiveRecord save and you're not even saving doing anything in that method.
call
super(upload)
in your save method (should be the first line)
回答2:
You are overriding the ActiveRecord save method with your custom self.save
class method. Also, I'd recommend using an upload gem like paperclip or something similar
回答3:
I have find the solution. Manually added image original file name in Post.create function.
Controller code :
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
Modle Code :
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
来源:https://stackoverflow.com/questions/19665395/image-name-not-inserted-into-database-in-ruby-on-rails