In my Ruby on Rails project, I use a uploader for images with carrier wave and minimagick. Through my site I do use it a couple of times. But I want to limit the amount of image's on a page. Therefore the user of the cms can't upload for example more than 2 images on the homepage and 3 on the contact page.
On another answer I found an Limit, caused by the model. But I would like to determine the amount of images per page. So in my opinion this only can be done in the view for every page to approach them separately.
The code for showing images is:
<% for attachment in @page.attachments %>
<div class="painting">
<%= image_tag attachment.image_url if attachment.image? %>
<div class="name"><%= attachment.name %></div>
<div class="actions">
<%= link_to "edit", edit_attachment_path(attachment) %> |
<%= link_to "remove", attachment, :confirm => 'Are you sure?', :method => :delete %>
</div>
</div>
I also found this
<%= image_tag attachment.image_url[0,1] if attachment.image? %>
For showing only for example the first image, but i doesn't work anymore (it did, strangely enough).
EDIT Use in models:
page.rb
class Page < ActiveRecord::Base
attr_accessible :name, :title, :body, :image, :text1, :text2, :text3, :text4
has_many :attachments
end
event.rb
class Event < ActiveRecord::Base
attr_accessible :image, :name, :date, :description, :event_id
has_many :attachments
has_many :event_attendees
has_many :attendees, :through => :event_attendees, :source => :user
validates_presence_of :name, :date
end
attachment.rb
class Attachment < ActiveRecord::Base
IMAGE_SIZES = {
:default => [280, 480],
:mini => [300,900],
:home => [200, 100]
}
attr_accessible :event_id, :page_id, :name, :image, :remote_image_url, :size
belongs_to :event
belongs_to :page
mount_uploader :image, ImageUploader
end
The way I see this is as follows:
To maintain the user experience, you'd want to store unlimited attachments, and limit the number of attachments at model level (on callback)
Join Model
I'd have a
many-to-many
relationship in a polymorphic join-model, like this:This will allow you to associate as many images with as many pages as you like, and also means you can limit the returned images per page
View
You'd call the images like this:
Of course you could limit at upload-level, but this would prevent the user from being able to have as many images as they like. At least by limiting on the model level, you'll be able to have as many images as you wish
Here's a good reference for you: limit the number of objects returned in a has_many