【发布时间】:2011-04-30 16:02:59
【问题描述】:
我为我的应用程序创建了一个留言板,并使用以下三种模型来完成整个工作:论坛有很多主题,主题有很多帖子。 Posts 是 Topic 的嵌套资源,每当用户选择“创建新主题”时,“new”操作都有一个嵌套的帖子来启动线程。这是那个的相关代码...
topics_controller.rb
class TopicsController < ApplicationController
load_and_authorize_resource
def new
@topic = Topic.new
@post = @topic.posts.build
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @topic }
end
end
[...]
topic.rb
class Topic < ActiveRecord::Base
has_many :posts
belongs_to :user, :counter_cache => TRUE
belongs_to :forum, :counter_cache => TRUE
validates :title, :length => { :maximum => 95 }, :presence => { :message => "You need to title your topic." }
accepts_nested_attributes_for :posts
end
post.rb
class Post < ActiveRecord::Base
belongs_to :user, :counter_cache => TRUE
belongs_to :forum, :touch => TRUE, :counter_cache => TRUE
belongs_to :topic, :touch => TRUE, :counter_cache => TRUE
validates :body, :presence => { :message => "You have not written any text in the body." }
end
new.html.erb
<%= form_for(@topic, :url => forum_topics_path) do |f| %>
<%= f.label :title %><%= f.text_field :title %>
<%= fields_for(@post) do |cf|%>
<%= cf.label :body %><%= cf.text_area :body, :cols=> 108, :rows => 10 %>
<% end %>
<%= f.submit %>
<% end %>
无论如何,我完成了这个并且效果很好。
到现在为止。突然间我无缘无故地发现,每当我选择“创建新主题”并定向到主题上的“新”操作时,我都会收到“主题中的 NoMethodError #new:你有一个 nil 对象”的错误当你没想到的时候!你可能期待一个 Array 的实例。在评估 nil 时发生错误。[]"
这完全没有意义,因为我回顾了 git 中的以前版本,并且没有对这段代码进行任何惊天动地的更改。也许是某些更新的 Rails 版本(3.0.7)或 Gem 负责,但我不知道。
不管怎样,它适合的行是在 html.erb 文件中,。呃......它是新的,所以它应该是零,对吧?把它拿出来,它就起作用了。我尝试将主题控制器中的@post 重新定义为 Post.new,但这会返回相同的错误。此外,我在这个主题上搜索的任何内容都说@post = @topic.posts.build 是要走的路。
那么我在上面的代码中做错了吗?知道为什么它以前可以工作,但现在不行吗?
【问题讨论】:
标签: ruby-on-rails controller nested-attributes