我有一个Class House,它有很多house_photos。我创建了大量照片(@mainentrance
),用户可以使用house.photo
选择radio button
。为此,我有一个带form_tag
的嵌套表单。我试着关注这篇文章(Using a Form_for with an each loop),但它没有用,因为我有一个嵌套的表单。
以下是代码:
<%= form_tag new_house_path do |f| %>
<div class="col-md-3 detailsnew">
<div class="field">
<%= text_field :title, :autofocus => true, class: 'form-control' %>
</div>
</div>
<div class="col-md-12">
<h3> Main Entrance </h3>
<%= fields_for :house_photos, @houses.house_photos do |house_photo| %> <!-- nested form-->
<%= house_photo.hidden_field :title, :value => "Main Entrance" %><br /> <!-- title house_photo -->
<% @mainentrance.each do |photo| %> <!-- render all image users can select -->
<a class="fancybox-thumb" rel="fancybox-thumb" href="<%= photo.attachment %>"><img src="<%= photo.attachment %>" alt="" style ="margin: auto; display: inline-block; padding: 5px 0px; height: 200px; width: 300px;"/></a>
<%= fields_for "house_photo[#{photo.id}]", photo do |p| %>
<%= house_photo.radio_button 'attachment', class: 'form-control', :value => p.attachement %> <!-- radio_button for each photo -->
<% end %>
<% end %>
<div class="col-md-12 actions" >
<%= f.submit "Submit house", :class => "btn btn-small btn-primary", :style => "color:#ffffff" %>
</div>
<% end %>
基本上,我正在尝试将@mainentrance
的值附件用于house_photo
。
使用此代码,我收到错误Undifined method 'attachment' for #<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations...>
答案 0 :(得分:0)
我使用form_for修复了问题。 这篇文章非常有用Rails form with multiple nested models causes issues with radio groups
这是一个很好的代码:
<%= form_for(@houses) do |f| %>
<div class="col-md-3 detailsnew">
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title, :autofocus => true, class: 'form-control' %>
</div>
</div>
<div class="col-md-12">
<h3> Main Entrance </h3>
<%= fields_for :house_photos, @houses.house_photos do |house_photo| %> <!-- nested form-->
<%= house_photo.hidden_field :title, :value => "Main Entrance" %><br /> <!-- title house_photo -->
<% @mainentrance.each do |photo| %> <!-- render all image users can select -->
<a class="fancybox-thumb" rel="fancybox-thumb" href="<%= photo.attachment %>"><img src="<%= photo.attachment %>" alt="" style ="margin: auto; display: inline-block; padding: 5px 0px; height: 200px; width: 300px;"/></a>
<!-- Solution -->
<%= house_photo.radio_button(:imageurl, photo.attachment) %>
<% end %>
<div class="col-md-12 actions" >
<%= f.submit "Submit house", :class => "btn btn-small btn-primary", :style => "color:#ffffff" %>
</div>
<% end %>
</div>