rails active model to store data in an a file along with the database
I have a form and when its posted, some of its data gets saved into the database using the rails model. Along with the database, I need to store some of the content into a file. Can I enhance the "save" method in the model to write the content to the file? Is this a good design. If not what would be ideal design.
Continuing on this, I want to set the location where this file is stored, in the application configuration. Which file should I define this variable for the file location and how do I a开发者_JAVA百科ccess it in the model/controller
Thanks Kiran
You can of course use one of the existing, ready-made file-attachment libraries, such as paperclip and carrierwave.
Otherwise, you can:
# config/application.rb
# ...
config.my_app.cache_file_prefix = "/tmp/files"
# app/models/my_model.rb
class MyModel < ActiveRecord::Base
# Causes ActiveRecord to run this method
# before saving (creating or updating).
before_save :copy_to_file
private
def copy_to_file
# Write data to the file.
file_name = copy_to_file_name
File.open(file_name) do |f|
f.write("some data")
end
end
def copy_to_file_name
# Calculate and return the expected file name.
prefix = Rails.configuration.my_app.cache_file_prefix
"#{prefix}/#{id}"
end
end
Please note that this solution will not work once you have more than one server running your Rails application. You should consider using either an object storage provider (such as S3 or Rackspace) or a replicated or distributed file system (such as DRDB or GlusterFS).
精彩评论