First, I'm very new to Rails, and Stack Overflow, and currently bushwhacking my way through the learning curve, so I apologize if my post is laughably noobish. Here's my problem:
I'm trying to build a blog from scratch using Amazon s3 to store resources, such as all the images and text. I have no need for Users uploading stuff to the site, so I figure I can just upload everything manually to s3 using their console at console.aws.amazon.com. I'm trying to code Rails to read folders from my s3 bucket and then point the images/text to the right spots in the database. For example, I could make a folder called "Post1" in s3, then my Rails app reads the URL of everything from inside that folder and points it to post1 in the database, then I can simply call up the image URL, or text, in the view and, theoretically, display it. My question is, how do I get my app to read s3 folders?
I know I'm probably reinventing the wheel here, but my goal is also to learn Rails. Thanks everyone in advance. You can find my project on GitHub.
My blog model:
class BlogPost < ActiveRecord::Base
has_attached_file :download,
:storage => :s3,
:s3_credentials => Proc.new{|a| a.instance.s3_credentials }
def s3_credentials
{:bucket => "S3_BUCKET_NAME", :access_key_id => "AWS_ACCESS_KEY_ID", :secret_access_key => "AWS_SECRET_ACCESS_KEY"}
end
end
Here is my blog controller:
class BlogController < ApplicationController
before_action :load_posts
def index #this method puts all the stuff pulled from 'load_posts' and packages it nicely in a instanced variable
@blogPosts = BlogPost.all
end
def load_posts #this method should pull posts from AWS s3 and add them to the database (like magic)
end
end
I'm sure there are gaping holes in my code...like something to actually talk to s3. I know the bulk of what I want to do probably goes in my model. I feel really stuck. I'm hoping there's some simple, magical Ruby method that I can use, like s3.file.read or something. Another option would be to create a form for myself, as though I'm a User, that connects everything together in the database, then uploads to s3. Yet, I've read people run into issues, like dynos timing out, when they try to upload large files (like big images) through heroku and onto s3. I've read tutorials on how to upload directly to s3, but I might as well skip that process and just click the 'upload' button on the s3 console. Anything will help. Thanks again all.
You are using the aws-sdk, good, I'll hit you with the s3.file.read equivalent then: Aws::S3::Object#get.
# create your bucket first
s3_file = bucket.object['myfile.txt'].get({response_target: '/tmp/myfile.txt'})
I think you can then do s3_file.body.
Lastly, you are re-inventing the wheel and should check-out carrierwave with aws-sdk.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With