我正在做Ruby101教程,但是出了点问题。
rails log:
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:in
block in _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&#39; 在救援/布局中渲染/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(3.7ms) 渲染/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.5ms) 渲染/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) 在救援/布局(21.5ms)内呈现/home/zedong/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb
和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
答案 0 :(得分:1)
您需要确保group
与post
相关联,您可以仅使用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%>