嵌套表单fields_for text_area未显示

时间:2012-11-26 15:43:36

标签: ruby-on-rails nested-attributes

我有三层模型:

用户has_many要求has_many结果

在主页上,我希望用户能够在完成时将结果添加到他们的询问中。我正在尝试使用嵌套表单在Ask表单中显示Outcome描述,该表单还会更新done标志和完成日期。

与SO上的其他用户/问题一样,我无法在屏幕上显示嵌套表格。我已经按照其他问题的说明进行操作,但仍然没有显示嵌套字段。我想知道是否有人能在下面的代码中发现问题?

询问模型

class Ask < ActiveRecord::Base

  attr_accessible   :category, :description, :done, :followed_up, 
                    :helper, :public, :date_done, :date_followed_up, :user_id, :outcomes_attributes
  belongs_to :user, counter_cache: true
  has_many :outcomes
  accepts_nested_attributes_for :outcomes

end

询问控制器

class AsksController < ApplicationController

  def new
    @ask = current_user.asks.build(params[:ask])
    @ask.outcomes.build
  end

  def create
    @ask = current_user.asks.build(params[:ask])
    if @ask.save!
      respond_to do |format|
        format.html { redirect_to edit_ask_path(@ask) }
        format.js
      end
    else
      flash[:error] = "Something is wrong. The Ask was not saved..."
    end
  end

  def edit
    @ask = current_user.asks.find(params[:id])
  end

  def update
    @ask = current_user.asks.find(params[:id])
    @ask.outcomes.build
    @ask.update_attributes(params[:ask])
    respond_to do |format|
      format.html { redirect_to edit_ask_path(@ask) }
      format.js
    end
  end
end

主页控制器 (此表单在主页上)

class StaticPagesController < ApplicationController

  def home
    if signed_in?
      @ask = current_user.asks.build(params[:ask])
      @ask.outcomes.build
    end
  end

在主页上呈现的部分表格

<% if current_user.asks.any? %>
  <ul id="ask-list-items">
    <% current_user.asks.where(done: false).each do |a| %> 
          <%= form_for(a) do |f| %>
            <li><%= a.description %></li>
            <%= f.hidden_field :date_done, value: Date.today %>
            <%= f.hidden_field :done, :value=>true %>
            <%= f.submit "Mark as done", class: "btn btn-small hidden done_btn", id: "a-#{a.id}-done" %>

            <%= f.fields_for :outcomes do |builder| %> # << These fields are not showing up
              <%= builder.text_area :description, placeholder: "Describe the outcome...", id: "ask-message" %>
            <% end %>
            <%= f.submit "Save outcome", class: "btn btn-primary" %>
          <% end %>
    <% end %>
  </ul>
<% end %>

1 个答案:

答案 0 :(得分:3)

form_forfields_for中使用符号时,Rails尝试使用具有相同名称的实例变量,例如@outcomes :outcomes。所以尝试(对于现有结果):

<% @outcomes = a.outcomes %>
f.fields_for :outcomes...行前的

对于新成果:

<% @outcomes = a.outcomes.build %>

(最后一个对问题所有者的贡献)