我有一个照片模型和一个画廊模型。画廊模型(我使用了漂亮的脚手架)只有一个字段,即画廊名称。在我的照片编辑表单中,我想将每张照片链接到一个图库,例如。我创建了2个独立的画廊2009和2010年,我想有一个下拉列表在每个照片编辑页面上的画廊列表,这样每一张照片都可以放在一个画廊。我一直使用this和this作为起点,但我被卡住了,无法让图库出现在我的照片形式中。
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视图/照片/_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 %>目前在照片表单页面上没有下拉列表,尽管我没有收到任何错误,在页面源代码中也没有提到它。我很感激任何人的帮助或者被指引到正确的方向...
发布于 2010-07-09 01:21:49
如果你的照片属于图库,那么照片上的gallery_id不是吗?所以gallery_id应该是photo_form的成员,而不是gal_form的成员。
<%= photo_form.collection_select :gallery_id, Gallery.all, :id, :name %> 更新:
下面是我如何看待你的观点:
<% 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 %>您的模型:
class Gallery < ActiveRecord::Base
has_many :photos
end
class Photo < ActiveRecord::Base
belongs_to :gallery
end发布于 2010-07-09 01:50:29
听起来你不需要嵌套表单。我会完全放弃accepts_nested_attributes_for。
工作流程应该是: 1)选择一个图库2)上传和描述照片
您可以使用单独的控制器/视图来管理图库。
一旦你做到了这一点并验证了你的模式,上面的例子就可以工作了(直接绑定到照片的图库上的集合选择)
发布于 2010-07-09 03:32:34
@拉斐尔:
列名应为gallery_id(model名称+ id),添加后
在ruby控制台中尝试下面这行代码。
photos = Photo.find_all_by_gallery_id(Gallery.first)这将为您提供第一个图库中所有照片的列表。
https://stackoverflow.com/questions/3206161
复制相似问题