I’m working on a simple photo gallery in rails, it seems to be a good
project for a newbie.
I have photos and categories, many-to-many association. It worked well
with HABTM. Then I decided that it would be good to be able to change
order of the photos so that thumbnail pages would look less chaotic.
So I created a Layout model which is a join model (or whatever it is
called) that replaces HABTM relation. It has photo_id, category_id and
position. Photo has many layouts and many categories through layouts.
Category is analogous.
In this way I obtained a structure that works as the one before with one
exception: there is no Photo.categories= method when :through is used.
After hours of googling (no-one gives examples of creating/editing data
for such relationship, the documentation just says that
collection=objects method exists) I gave up and wrote my own accessor:
collection.find_all do |category|
layout = self.layouts.build(:category => category)
self.layouts << layout
Some questions arise however:
- Is there other possibility, more “standard”, that I could use to
replace categories in photo with those from user form?
- If not, then what do you think about this solution (I’m new to both
Rails and Ruby)?
- Is my abstraction correct? Maybe there is no collection= method
because it the proper solution of my problem doesn’t need it? Here are
some more details:
Each photo can have many categories.
Each category has many photos.
There is only one layout per category.
When user edits a photo (s)he selects categories in which it should be
present. List of selected categories is assigned into photo.categories.
This operation should also create a layout that binds this photo with
selected categories - regular many-to-many relationship.
My solution doesn’t take the layout, ie. the acts_as_list part, into
account. Maybe when I start implementing it, the whole situation