问题是我有一个表格,通常应该渲染当前汽车的照片,但它会这样做,但它会多次渲染..像这样:我有5张照片为car_id 2而在屏幕上我有5次这些照片显示。
12345 12345 12345 12345 12445
如果我添加照片,那么它将被曝光6次。问题是什么以及如何解决它,我已经尝试了很多:替换它,替换它但没有。
以下是表单本身的一部分
<%= form_for @car, :html => { :method => :put }, :html => { :multipart => true } do |f| %>
...
...
<% for photo in @car.uploads %>
<div style="width:750px !important;">
<%= f.fields_for :uploads do |photo_fields| %>
<%unless photo_fields.object.new_record? %>
<div style="width:150px;float:left;">
<%= image_tag(photo_fields.object.photo.url(:thumb)) %>
<p><%= photo_fields.check_box :_destroy %> Delete item</p>
</div>
<% end %>
<% end %>
</div>
....
...
<% end %>
和控制台:
Started GET "/cars/2/edit" for 127.0.0.1 at Sun Nov 06 22:50:17 +0200 2011
Processing by CarsController#edit as HTML
Parameters: {"id"=>"2"}
User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
SQL (4.1ms) SHOW TABLES
Car Load (0.2ms) SELECT `cars`.* FROM `cars` WHERE `cars`.`id` = 2 LIMIT 1
CACHE (0.0ms) SELECT `cars`.* FROM `cars` WHERE `cars`.`id` = 2 LIMIT 1
Carname Load (0.2ms) SELECT `carnames`.* FROM `carnames`
Carmodel Load (0.2ms) SELECT `carmodels`.* FROM `carmodels`
Rendered shared/_error_messages.html.erb (1.0ms)
Upload Load (0.2ms) SELECT `uploads`.* FROM `uploads` WHERE (`uploads`.car_id = 2)
Carname Load (0.2ms) SELECT `carnames`.* FROM `carnames` WHERE `carnames`.`id` = 1 LIMIT 1
Carmodel Load (0.2ms) SELECT `carmodels`.* FROM `carmodels` WHERE `carmodels`.`id` = 5 LIMIT 1
Rendered uploads/_upload.html.erb (8.1ms)
Rendered cars/_show.html.erb (2.7ms)
WARNING: Can't mass-assign protected attributes: user_id
Rendered cars/_form.html.erb (460.6ms)
Rendered welcome/_sliderempty.html.erb (1.0ms)
Rendered welcome/_footer.html.erb (0.5ms)
感谢您的时间。
答案 0 :(得分:1)
只需删除for循环,fields_for
已遍历照片,因此您需要迭代两次才能获得两次照片。
回复你的评论:尝试明确地传递集合,如:
<%= f.fields_for :uploads, @car.uploads do |photo_fields| %>
所以你走了:
<%= form_for @car, :html => { :method => :put }, :html => { :multipart => true } do |f| %>
...
...
<div style="width:750px !important;">
<%= f.fields_for :uploads, @car.uploads do |photo_fields| %>
<%unless photo_fields.object.new_record? %>
<div style="width:150px;float:left;">
<%= image_tag(photo_fields.object.photo.url(:thumb)) %>
<p><%= photo_fields.check_box :_destroy %> Delete item</p>
</div>
<% end %>
<% end %>
</div>
....
...
<% end %>