我有一组嵌套模型用于存储各个房间的价格。
IE。
Places
Rooms
Room_rates
每个模型都有必要的 accept_nested_attributes_for 和 has_many belongs_to 关联,我有一个表单和一个构建方法,非常适合初始创建。
我的问题是如何制作一个更智能的控制器,如果它不存在则构建该字段,或者如果存在则从它读取(并且不构建它)。目前它仅适用于初始输入,否则它会尝试构建比可能更多的字段并在重新提交时中断。
def new
@place = Place.find(params[:place_id])
@rooms = @place.rooms
@rooms.each do |r|
7.times { r.room_rates.build } #days of the week
end
end
试过了
@rooms.each do |r|
7.times {
unless r.room_rates
r.room_rates.build
end
}
end
room_rates 数据库
id, room_id, dayofweek, price
形式
<% form_for @place do |f| %>
<%= f.error_messages %>
<table>
<tr>
<th>Room</th>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thu</th>
<th>Fri</th>
<th>Sat</th>
<th>Sun</th>
</tr>
<% f.fields_for :rooms do |room| %>
<% dow = 0 %>
<tr>
<td><%= room.text_field :name %></td>
<% room.fields_for :room_rates do |rates| %>
<td>
<%= rates.text_field :price %>
<%= rates.text_field :dayofweek, :value => dow %>
</td>
<% dow += 1 %>
<% end %>
</tr>
<% end %>
</table>
<%= f.submit "Submit" %>
<% end %>