开发者

rails build method for complex model with days of the week

I have a set of nested models for storing prices for individual rooms.

Ie.

  Places
    Rooms
      Room_rates

Each model has the necessary accepts_nested_attributes_for and has_many belongs_to association and I have a form and a build method which works perfectly for the initial creation.

My question is how to make a smarter controller, that either builds the field if it doesn't exist, or reads from it if it does (and doesn't build it). Currently it only works for the initial input, otherwise it attempts to build more fields than are possible and breaks on resubmission.

  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

tried

@rooms.each do |r|
  7.times { 
    unless r.room_rates
      r.room_rates.build
    end 
  }
end

database for room_rates

id, room_id, dayofweek, price

form

<% form_for @place do |f| %>
  <%= f.error_messages %>


<table>
  <tr>  
    <th>Room</th>
    <th>Mon</th>
    <th>Tue</th>
    <th>Wed</th>
    <开发者_JAVA技巧;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 %>


You can try:

@rooms.each do |r|
  ((r.room_rates.size+1)..7).each {   
      r.room_rates.build       
  }
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜