Reputation: 7314
I have a photos model and a gallery model. The gallery model(I used nifty scaffold) just has one field, a gallery name. In my photo edit form I want to link each photo to a gallery, eg. I create 2 separate galleries 2009 and 2010, I want to have a dropdown list on each photo edit page with the list of galleries, so each photo can be placed in a gallery. I've been using this and this as starting points but I'm stuck, and can't get the galleries to appear in my photo form.
class Gallery < ActiveRecord::Base
has_many :photos
attr_accessible :name
end
class Photo < ActiveRecord::Base
belongs_to :gallery
accepts_nested_attributes_for :gallery, :allow_destroy => true
views/photos/_form.html.erb
<% form_for @photo, :html => { :multipart => true } do |photo_form| %>
<p>
<%= photo_form.label :title %><br />
<%= photo_form.text_field :title %>
</p>
<p>
<% photo_form.fields_for :gallery do |gal_form| %>
<%= gal_form.label :name %>
<%= gal_form.collection_select :gallery_id, Gallery.all, :id, :name %>
</p>
<% end %>
<p>
<%= submit_tag %>
</p>
<% end %>
Currently there is no dropdown list on the photo form page, though I'm not receiving any errors and there is no mention of it either in the page source. I'd appreciate any help or to be pointed in the right direction...
Upvotes: 0
Views: 1289
Reputation: 278
@Raphael:
The column name should be gallery_id(model name + id), after adding it
Try this below line in your ruby console
photos = Photo.find_all_by_gallery_id(Gallery.first)
This should give you list of all photos in the first gallery.
Upvotes: 0
Reputation: 7500
If your photo belongs to the gallery then isn't the gallery_id
on the photo? So the gallery_id would be a member of the photo_form
not the the gal_form
.
<%= photo_form.collection_select :gallery_id, Gallery.all, :id, :name %>
UPDATE:
Here is how I would see your view:
<% form_for @photo, :html => { :multipart => true } do |photo_form| %>
<p>
<%= photo_form.label :title %><br />
<%= photo_form.text_field :title %><br />
<%= photo_form.collection_select :gallery_id, Gallery.all, :id, :name %>
</p>
<p>
<%= submit_tag %>
</p>
<% end %>
Your model:
class Gallery < ActiveRecord::Base
has_many :photos
end
class Photo < ActiveRecord::Base
belongs_to :gallery
end
Upvotes: 2
Reputation: 19145
It sounds like you don't need a nested form. I would drop accepts_nested_attributes_for entirely.
The work flow should be: 1) select a gallery 2) Upload and describe photo
You can have a separate controller/view for managing galleries.
Once you've done that and verified your schema, the example above should work (collection select on galleries tied directly to Photo)
Upvotes: 0