从另一个模型渲染部分视图

6
我有一个Rails应用程序,模拟了一座房子。有一个房屋模型,具有许多参数,并且它has_many rooms。一个房间有一个house_id和一个名称。我还使用了http://github.com/ryanb/complex-form-examples来允许向房间添加许多灯和small_appliances。complex-form-example使用RJS和partials来实现这一点。
有一个名为计算器的控制器,用户将使用该控制器访问应用程序。当单击计算器上的提交按钮时,它会重定向到一个add_rooms页面(位于app/views/calculator/add_rooms.html.erb),在该页面中用户可以向房屋添加房间。add_rooms页面使用了app/views/rooms/_room_form.html.erb中的一个partial。我无法让它显示出来,因为Rails总是在app/views/calculator文件夹中寻找内容。
我该如何让它显示?请注意,保存房间时需要保存房屋的id。
以下是所有相关代码(希望如此):

更新

如果我注释掉这两个add_child_link,页面就可以渲染。但是,当我点击提交时,会出现一个新的错误信息:

在CalculatorController#add_room中,期望的是SmallAppliance(#49096610),但实际得到的是Array(#1560620)。
RAILS_ROOT: C:/Users/ryan/Downloads/react 应用程序跟踪 | 框架跟踪 | 完整跟踪
C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.4/lib/active_record/associations/association_proxy.rb:263:in `raise_on_type_mismatch' C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.4/lib/active_record/associations/association_collection.rb:320:in `replace' C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.4/lib/active_record/associations/association_collection.rb:320:in `each' C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.4/lib/active_record/associations/association_collection.rb:320:in `replace' C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.4/lib/active_record/associations.rb:1322:in `small_appliances=' C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.4/lib/active_record/base.rb:2744:in `send' C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.4/lib/active_record/base.rb:2744:in `attributes=' C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.4/lib/active_record/base.rb:2740:in `each' C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.4/lib/active_record/base.rb:2740:in `attributes=' C:/InstantRails/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.4/lib/active_record/base.rb:2438:in `initialize' C:/Users/ryan/Downloads/react/app/controllers/calculator_controller.rb:31:in `new' C:/Users/ryan/Downloads/react/app/controllers/calculator_controller.rb:31:in `add_room'
如果我删除 small_application 部分,对于 light 也会发生相同的事情。我认为这与 room 模型中的 accepts_nested_attributes_for 有关。我已经添加了下面的代码。我还添加了 house.rb 的代码。

app/models/room.rb

class Room < ActiveRecord::Base
  belongs_to :house
  has_many :lights, :dependent => :destroy
  has_many :small_appliances, :dependent => :destroy
  validates_presence_of :name
  accepts_nested_attributes_for :lights, :reject_if => lambda { |a| a.values.all?(&:blank?) }, :allow_destroy => true
  accepts_nested_attributes_for :small_appliances, :reject_if => lambda { |a| a.values.all?(&:blank?) }, :allow_destroy => true         
end

app/models/house.rb

class House < ActiveRecord::Base
  has_many :rooms

  # validation code not included

  def add_room(room)
    rooms << room
  end

end

app/controllers/calculator_controller.rb

class CalculatorController < ApplicationController
  def index
  end

  def save_house
    @house = House.new(params[:house])
    respond_to do |format|
      if @house.save
        format.html { render :action => 'add_rooms', :id => @house }
        format.xml { render :xml => @house, :status => :created, :location => @house }
      else
        format.html { render :action => 'index' }
        format.xml  { render :xml => @house.errors, :status => :unprocessable_entity }
      end
    end
  end

  def add_rooms
    @house = House.find(params[:id])
    @rooms = Room.find_by_house_id(@house.id)

  rescue ActiveRecord::RecordNotFound
    logger.error("Attempt to access invalid house #{params[:id]}")
    flash[:notice] = "You must create a house before adding rooms"
    redirect_to :action => 'index'
  end

  def add_room
    @house = House.find(params[:id])
    @room = Room.new(params[:room])

    respond_to do |format|
      if @room.save
        @house.add_room(@room)
        @house.save
        flash[:notice] = "Room \"#...@room.name}\" was successfully added."
        format.html { render :action => 'add_rooms' }
        format.xml { render :xml => @room, :status => :created, :location => @room }
      else
        format.html { render :action => 'add_rooms' }
        format.xml  { render :xml => @room.errors, :status => :unprocessable_entity }
      end
    end
  rescue ActiveRecord::RecordNotFound
    logger.error("Attempt to access invalid house #{params[:id]}")
    flash[:notice] = "You must create a house before adding a room"
    redirect_to :action => 'index'
  end

  def report
    flash[:notice] = nil
    @house = House.find(params[:id])
    @rooms = Room.find_by_house_id(@house.id)
  rescue ActiveRecord::RecordNotFound
    logger.error("Attempt to access invalid house #{params[:id]}")
    flash[:notice] = "You must create a house before generating a report"
    redirect_to :action => 'index'
  end

end

app/views/calculator/add_rooms.html.erb

<div id="addRooms">
  <p>House id is <%= @house.id %></p>

  <h3>Your rooms:</h3>
  <% if @house.rooms %>
  <ul>
    <% for room in @house.rooms %>
    <li>
      <%= h room.name %> has <%= h room.number_of_bulbs %>
      <%= h room.wattage_of_bulbs %> watt bulbs, in use for
      <%= h room.usage_hours %> hours per day.
    </li>
    <% end %>
  </ul>
  <% else %>
  <p>You have not added any rooms yet</p>
  <% end %>

  <%= render :partial => 'rooms/room_form' %>

  <br />
  <%= button_to "Continue to report", :action => "report", :id => @house %>
</div>

app/views/rooms/_room_form.html.erb

<% form_for :room, :url => { :action => :add_room, :id => @house } do |form| %>
  <%= form.error_messages %>
  <p>
    <%= form.label :name %><br />
    <%= form.text_field :name %>
  </p>

  <h3>Lights</h3>
  <% form.fields_for :lights do |light_form| %>
    <%= render :partial => 'rooms/light', :locals => { :form => light_form } %>
  <% end %>
  <p class="addLink"><%= add_child_link "[+] Add new light", form, :lights %></p>

  <h3>Small Appliances</h3>
  <% form.fields_for :small_appliances do |sm_appl_form| %>
    <%= render :partial => 'rooms/small_appliance', :locals => { :form => sm_appl_form } %>
  <% end %>
  <p class="addLink"><%= add_child_link "[+] Add new small appliance", form, :small_appliances %></p>

  <p><%= form.submit "Submit" %></p>
<% end %>

application_helper.rb

module ApplicationHelper
  def remove_child_link(name, form)
    form.hidden_field(:_delete) + link_to_function(name, "remove_fields(this)")
  end

  def add_child_link(name, form, method)
    fields = new_child_fields(form, method)
    link_to_function(name, h("insert_fields(this, \"#{method}\", \"#{escape_javascript(fields)}\")"))
  end

  def new_child_fields(form_builder, method, options = {})
    options[:object] ||= form_builder.object.class.reflect_on_association(method).klass.new
    options[:partial] ||= method.to_s.singularize
    options[:form_builder_local] ||= :form
    form_builder.fields_for(method, options[:object], :child_index => "new_#{method}") do |form|
      render(:partial => options[:partial], :locals => { options[:form_builder_local] => form })
    end
  end
end

谢谢,
Ryan

3个回答

5
非常奇怪 - 如果您写<% = render:partial => 'room_form'%>% ,则Rails将认为它是 app / views / calculator / _room_form.html.erb ,但在<%= render:partial =>'rooms / room_form'%>的情况下,它将认为它是 app / views / rooms / _room_form.html.erb 。
注意日志 - 在那里,您将看到呈现了哪些部分。

当我使用render:partial =>'rooms/room_form'时,我会收到以下错误信息:显示app/views/rooms/_room_form.html.erb,其中第13行引发了错误: 未定义方法“reflect_on_association”用于NilClass:Class这来自add_child_link调用。我已经将application_helper.rb添加到原始帖子中。 - Ryan

1
问题在于当您尝试添加子链接时,没有定义room对象。
render :partial => 'rooms/room_form', :object => Room.new

1

我知道这个问题很旧,但我遇到了同样的问题并成功解决了它。

具体来说,我也在跟随 Ryan Bates 的复杂表单示例。

我的表单没有以相同的错误呈现:

undefined method `reflect_on_association' for NilClass:Class

我将add_child_link助手注释掉后,表单成功渲染,但在提交时出现了以下错误:

ChildModel expected, got Array

经过长时间的思考,我做了一个简单的改变,解决了所有问题:

-- form_for :project
++ form_for @project

没错,仅仅是更改实例变量的符号就让它能够正常工作了。

希望这能帮助其他遇到问题的人。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接