在one_of_many-to-one关联中使用表单的新操作

时间:2014-06-03 19:07:26

标签: ruby-on-rails associations nested-forms nested-attributes

无法弄清楚如何渲染新动作。当我尝试加载新动作时,我会收到下一个错误 - undefined method 'hotel' for nil:NilClass

我的旅行,酒店经销商和酒店模特

class Trip < ActiveRecord::Base
  has_many :hotelsellers, :dependent => :destroy

  attr_accessible :hotelsellers_attributes, :description
  accepts_nested_attributes_for :hotelsellers, :reject_if => lambda { |a| a.blank? }
end

class Hotelseller < ActiveRecord::Base
  belongs_to :trip
  has_one :hotel

  attr_accessible :hotel_attributes,
  accepts_nested_attributes_for :hotel, :reject_if => lambda { |a| a.blank? }
end


class Hotel < ActiveRecord::Base
  belongs_to :hotelseller

  attr_accessible :description
end

我的控制器 trips_controller.rb

def new
  hotelseller_first = @trip.hotelsellers.build(five_stars: false)
  hotelseller_second = @trip.hotelsellers.build(five_stars: true)
  @hotel = @trip.hotelsellers.build.build_hotel
end

我的表单 new.html.erb

<%= simple_form_for(@trip) do |f| %>
  <%- f.description %>
  <%= f.fields_for :hotelsellers do |builder| %> 

    <% if builder.object.five_stars %>
      First hotel
      <%= builder.hidden_field :five_stars, value: true %>
    <% else %>
  Second hotel
  <%= builder.hidden_field :five_stars, value: false %>
    <% end %>
    <%= builder.descritpion %>

    <%= builder.simple_fields_for :hotel do |builder| %>    
      <%= builder.description %>
    <% end %>

  <% end %>
<% end %>

1 个答案:

答案 0 :(得分:0)

我应该将builder.simple_fields_for:hotel更改为builder.simple_fields_for:hotel_attributes