Rails:无法使fields_for在嵌套资源中工作

时间:2010-10-24 13:33:26

标签: ruby-on-rails nested-forms fields-for

我正在尝试将fields_for属性添加到嵌套的rails表单中。每当我尝试创建一个新对象时,它都会返回

  

消息(#58819400)预计,得到了   数组(#18​​903800)......

     

应用程序/控制器/ discussions_controller.rb:53:在   `创建'

如果我尝试从基于非嵌套资源的表单访问嵌套的fields_for(又名“form_for @parent”而不是“form_for [@ parent,@ child]”,它可以正常工作。下面的代码 - 任何对此的帮助都非常感激

控制器:

  # GET /discussions/new
  # GET /discussions/new.xml
  def new
    @forum = Forum.find(params[:forum_id])
    @discussion = Discussion.new
    @discussion.messages.build

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @discussion }
    end
  end


  def create
    @forum = Forum.find_by_id(params[:forum_id])
    @discussion = @forum.discussions.new(params[:discussion])
    @discussion.user = current_user

    respond_to do |format|
      if @discussion.save
        format.html { redirect_to([@forum, @discussion], :notice => 'Discussion was successfu#ly created.') }
        format.xml  { render :xml => [@forum, @discussion], :status => :created, :location => @discussion }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @discussion.errors, :status => :unprocessable_entity }
      end
    end
  end

型号:

class Forum < ActiveRecord::Base
  belongs_to :user
  has_many :discussions, :dependent => :destroy
  validates :title, :presence => true

  accepts_nested_attributes_for :discussions, :allow_destroy => true
end

class Discussion < ActiveRecord::Base
  belongs_to :user
  belongs_to :forum
  has_many :messages, :dependent => :destroy
  validates :title, :presence => true
end

class Message < ActiveRecord::Base
  belongs_to :user
  validates :user, :presence => true
  validates :content, :presence => true
end

观点:

<%= form_for [@forum, @discussion] do |f| %>
  <% if @discussion.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@discussion.errors.count, "error") %> prohibited this discussion from being saved:</h2>

      <ul>
      <% @discussion.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  <%= f.fields_for :messages do |builder| %>
    <%= builder.label :content, "Message" %>
    <%= builder.text_area :content, :rows => 10 %>

  <% end %>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

最后,路由:

  resources :forums do
    resources :discussions do
      resources :messages
    end
  end

对此的任何帮助都非常感激 - 我完全被难过了。

1 个答案:

答案 0 :(得分:2)

Arghhh - 真的很抱歉...我刚刚意识到我在讨论模型中忘记了accepts_nested_attributes_for,&amp;因此论坛可以访问讨论,但讨论无法归结为消息。

无论如何,谢谢。