嵌套 def 编辑未定义方法错误
Nested def edit undefined method error
我有三个具有关系的模型:Forum
、Topic
和 Post
。我想编辑 Post
.
这是Post_controller:
def update
@forum = Forum.find params[:forum_id]
@topic = Topic.find params[:topic_id]
@post = @topic.posts.find(params[:id])
if @post.update(post_params)
redirect_to forum_topic_path(@forum.id, @topic.id)
end
end
def edit
@forum = Forum.find params[:forum_id]
@topic = Topic.find params[:topic_id]
@post = Post.find(params[:id])
end
这是edit.html.slim:
= simple_form_for ([@forum, @topics, @topics.posts.build]) do |f|
div.new_message
p
b Ответ в тему
= f.label 'Текст сообщения:'
= f.text_area :content,rows: '15', cols: '82'
div.forum_button
= f.submit 'Изменить'
这是错误:
NoMethodError in Posts#edit
undefined method `posts' for nil:NilClass
实例变量定义为 @topic
但 NOT @topics
在控制器的 edit
操作中。
这就是为什么您在调用时会收到上述错误的原因:@topics.posts.build
.
在您看来,您应该使用 @topic
而不是 @topics
:
= simple_form_for ([@forum, @topic, @topic.posts.build]) do |f|
需要修正两个地方:
将@topics 词替换为@topic
= simple_form_for ([@forum, @topic, @topic.posts.build]) do |f|
div.new_message
p
b Ответ в тему
= f.label 'Текст сообщения:'
= f.text_area :content,rows: '15', cols: '82'
div.forum_button
= f.submit 'Изменить'
希望对您有所帮助!
我有三个具有关系的模型:Forum
、Topic
和 Post
。我想编辑 Post
.
这是Post_controller:
def update
@forum = Forum.find params[:forum_id]
@topic = Topic.find params[:topic_id]
@post = @topic.posts.find(params[:id])
if @post.update(post_params)
redirect_to forum_topic_path(@forum.id, @topic.id)
end
end
def edit
@forum = Forum.find params[:forum_id]
@topic = Topic.find params[:topic_id]
@post = Post.find(params[:id])
end
这是edit.html.slim:
= simple_form_for ([@forum, @topics, @topics.posts.build]) do |f|
div.new_message
p
b Ответ в тему
= f.label 'Текст сообщения:'
= f.text_area :content,rows: '15', cols: '82'
div.forum_button
= f.submit 'Изменить'
这是错误:
NoMethodError in Posts#edit
undefined method `posts' for nil:NilClass
实例变量定义为 @topic
但 NOT @topics
在控制器的 edit
操作中。
这就是为什么您在调用时会收到上述错误的原因:@topics.posts.build
.
在您看来,您应该使用 @topic
而不是 @topics
:
= simple_form_for ([@forum, @topic, @topic.posts.build]) do |f|
需要修正两个地方:
将@topics 词替换为@topic
= simple_form_for ([@forum, @topic, @topic.posts.build]) do |f|
div.new_message
p
b Ответ в тему
= f.label 'Текст сообщения:'
= f.text_area :content,rows: '15', cols: '82'
div.forum_button
= f.submit 'Изменить'
希望对您有所帮助!