Deepu
Deepu

Reputation: 2616

How to upload image using paperclip without model in Rails 3?

I want to implement Papereclip in Rails 3.2 without a model.

I am very new to RoR and Paperclip.

I followed through THIS tutorial to use paperclip. It is running successfully.

But in this tutorial they have shown use of the model, I dont want to use the model or dont want to modify the existing model.

Upvotes: 2

Views: 3530

Answers (2)

Zedrian
Zedrian

Reputation: 909

Rails is object oriented.

# Article model
attr_accessible :image
# Paperclip attachment code and whatever rules and conditions you want.

The image attribute is actually a column from your database and an attribute accessible from your Article model. That image attribute will need to be a string type (varchar) to store the url where the image is saved.

For example if your article has an image attribute, in your view file Article#Show you can display your image through the article object with the image attribute as <%= image_tag @article.image.url %>.

If you want to have many images in a same article then you will want to create 2 models (Article and Image) and have an association where

 # Article model
 has_many :images
 accepts_nested_attributes_for :images

 # Image model
 attr_accessible :image_url
 belongs_to :article
 # paperclip attachments...

With this association you can then fetch and display your images by doing

<% @article.images.each do |image| %>
    <%= image_tag image.image_url.url %>
<% end %>

Technically you don't need to store the url of your image in the database, you can store it in variable, but then it will only be valid during the session and will disappear afterwards. If you want to view your image at a later date, then yes you need to store it in a database.

Upvotes: 3

Alok Swain
Alok Swain

Reputation: 6519

For not using a seperate model you can check Paperclip Docs. What is basically done here is that the image is stored as an atrribute of an existing model.

About not using a model at all, how do you want to associate the image object to some existing record ? Wont that be required in your project ?

Upvotes: 1

Related Questions