【问题标题】:Rails - nested loops inside viewRails - 视图内的嵌套循环
【发布时间】:2018-01-18 02:38:52
【问题描述】:

我将铁轨作为一种爱好,但我还是个新手,如果这听起来很荒谬,我深表歉意。我正在创建一个可以具有多种状态的板。每个状态可以有很多注释。但是,一旦我将注释循环添加到视图的状态循环中,就会出现此错误:

undefined method `notes' for nil:NilClass

boards/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

如果需要更多信息,请告诉我。谢谢你。 :)

【问题讨论】:

    标签: ruby-on-rails model-view-controller nested


    【解决方案1】:

    我认为它应该看起来更像:

    <% @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 %>
    

    这样您就可以在给定循环中使用来自statusnotes

    【讨论】:

    • 我之前用过这段代码,但还是报错。
    • 其实不用等,现在就可以了。谢谢!没有更多错误。
    • 太棒了!请随时投票和/或接受(对我和未来的 SO 搜索者有帮助)。
    【解决方案2】:

    您遇到的错误是因为在这一行 &lt;% @status.notes.each do |note| %&gt; 中,视图期望从板控制器中的 show 操作传递 @status 对象。由于您没有通过 @status,它是 nilnil 没有方法 notes

    正如@jvillian 指出的那样,它应该是&lt;% status.notes.each do |note| %&gt;,因为你想从你用each 在这一行中迭代的状态中获取注释:&lt;% @board.statuses.each do |status| %&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      • 2021-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多