首页 文章

Account :: Posts #index中的NoMethodError

提问于
浏览
0

我正在做Ruby101教程,但是出了点问题 .

rails日志:

ActionView::Template::Error (undefined method `title' for nil:NilClass):
13:       <% @posts.each do |post| %>
14:         <tr>
15:           <td> <%= post.content %> </td>
16:           <td> <%= post.group.title %> </td>
17:           <td> <%= post.updated_at %> </td>
18:           <td> <%= link_to('Edit', edit_group_post_path(post.group, post), class: "btn btn-default btn-xs") %></td>
19:           <td> <%= link_to('Delete', group_post_path(post.group, post), method: :delete, data: { confirm: "Are you sure?" }, class: "btn btn-default btn-xs") %></td>

app / views / account / posts / index.html.erb:16:在_app_views_account_posts_index_html_erb___92982360307258762_69918747126320'app / views / account / posts / index.html.erb:13:in_app_views_account_posts_index_html_erb ___92982360307258762_69918747126320'渲染/home/zedong/.rvm/gems救援/布局中的/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb渲染/home/zedong/.rvm/gems/ruby-2.3.1 /gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb呈现/home/zedong/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib /action_dispatch/middleware/templates/rescues/_source.html.erb(3msms)渲染/home/zedong/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates /rescues/_trace.html.erb呈现/home/zedong/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb(2.5 ms)渲染/home/zedong/.rvm/gems/ruby -2.3.1 / gems / actionpack-5.0.0.1 / lib / action_dispatch / middleware / templates / rescues / _request_and_response.html.erb呈现/home/zedong/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0 .0.1 / lib / action_dispatch / middleware / templates / rescues / _request_and_response.html.erb(0.7ms)呈现/home/zedong/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch /middleware/templates/rescues/template_error.html.erb救援/布局(21.5ms)

而group.rb:

class Group < ActiveRecord::Base
  belongs_to :user
  has_many :posts
  validates :title, presence: true
  has_many :group_relationships
  has_many :members, through: :group_relationships, source: :user
end

post.rb:

class Post < ApplicationRecord
  validates :content, presence: true
  belongs_to :user
  belongs_to :group

  scope :recent, -> {order("created_at DESC")}
end

因为我第二次做这个教程,所以我将它与第一次的代码进行比较 . 我试图逐个复制文件以找到问题,但它无法正常工作 . 顺便说一句,当我想实现eidt和删除按钮时,出了点问题 .

项目在这里:github

1 回答

  • 1

    您需要确保 postpost 关联,您可以使用 try 仅用于呈现纯内容(因此它不呈现任何内容,但不会引发异常):

    <td> <%= post.group.try(:title) %> </td>
    

    并且 if 控制流以有条件地呈现链接:

    <% if post.group.present? %>
      <td> <%= link_to('Edit', edit_group_post_path(post.group, post), class: "btn btn-default btn-xs") %></td>
      <td> <%= link_to('Delete', group_post_path(post.group, post), method: :delete, data: { confirm: "Are you sure?" }, class: "btn btn-default btn-xs") %></td>
    <%end%>
    

相关问题