我把铁杆作为一种爱好,但我仍然相当新,所以如果这听起来很荒谬,那就道歉了。我正在创建一个可以有很多状态的电路板。每个状态都可以有很多笔记。但是,一旦我将notes循环添加到视图的状态循环中,就会出现此错误:
undefined method `notes' for nil:NilClass
board / show.html.erb文件的片段:
<% @board.statuses.each do |status| %>
<div>
<h2><%= link_to status.name, status_url(status)%></h2>
<% @status.notes.each do |note| %>
<h2><%= link_to notes.content, note_url(note)%></h2>
<% end %>
<%= link_to 'New notes', new_note_path(@note) %>
</div>
<% end %>
我不确定我是否在控制器或视图中做错了。我一直很难搞清楚。我很感激任何帮助!
notes_controller :
class NotesController < ApplicationController
def new
@note = Note.new
end
def create
Note.create(note_params.merge(status_id: current_user.id))
redirect_to boards_url
end
def delete
Note.find(params[:id]).destroy(note_params)
end
def update
Note.find(params[:id]).update(note_params)
end
def note_params
params.require(:note).permit(:status_id, :content)
end
end
statuses_controller :
class StatusesController < ApplicationController
def new
@status = Status.new
end
def create
Status.create(status_params.merge(board_id: current_user.id))
redirect_to :root
end
def delete
Status.find(params[:id]).destroy(status_params)
end
def update
Status.find(params[:id]).update(status_params)
end
def show
@status = Status.find(params[:id])
end
def status_params
params.require(:status).permit(:board_id, :name)
end
end
需要更多信息然后告诉我。谢谢。 :)
答案 0 :(得分:0)
我认为它看起来应该更像:
<% @board.statuses.each do |status| %>
<div>
<h2><%= link_to status.name, status_url(status)%></h2>
<% status.notes.each do |note| %>
<h2><%= link_to notes.content, note_url(note)%></h2>
<% end %>
<%= link_to 'New notes', new_note_path(@note) %>
</div>
<% end %>
这样您就可以在给定循环中使用notes
中的status
。
答案 1 :(得分:0)
您获得的错误是因为在此行<% @status.notes.each do |note| %>
中,视图期望从板控制器中的@status
操作传递show
对象。由于您未传递@status
,因此nil
和nil
没有notes
方法。
正如@jvillian所指出的那样,它应该是<% status.notes.each do |note| %>
,因为您希望从此行中使用each
迭代的状态中获取注释:<% @board.statuses.each do |status| %>