0

所以昨天我遇到了一个问题,我无法在我的艺术家页面上显示来自朋友的评论,我已经设法解决了这个问题,但现在我正在努力在我的图像上显示评论。

我现在要做的就是显示我手动输入数据库的评论并将它们显示在我的图像下方。

这是图像的模型:

class Image < ActiveRecord::Base
  has_many :publishings
  has_many :artists, :through => :publishings
  has_many :comments,:through => :friends
  has_many :comments, :as => :resource, :class_name => "Commentable"
end

这是图像的 show.html

<p id="notice"><%= notice %></p>
<div id="container">
  <p>
    <b>Title:</b>
    <%= @image.title %>
  </p>

  <p>
    <b>Filename:</b>
    <%= @image.filename %>
    <%= image_tag @image.filename %>
  </p>

  <p>
    <b>Likes:</b>
    <span id="images_<$=@image.id%>_likes_count"><%= @image.likes %></span>
  </p>
  <div id="comments">
    <h2>Comments</h2> 
    <%= render :partial => "shared/comment", :collection => @image.comments%>
  </div>
</div>

<%= link_to 'Like', like_image_path(@image), :method => :post %> |
<%= link_to 'Edit', edit_image_path(@image) %> |
<%= link_to 'Back', images_path %>

这是我目前收到的错误:

> undefined method `first_name' for nil:NilClass

    Extracted source (around line #16):

13: </p>
14: <p>
15:   <b>First name:</b>
16:   <%= @artist.first_name %>
17: </p>
18: 
19: <p>

应用程序跟踪

app/views/images/show.html.erb:16:in `_app_views_images_show_html_erb___1549892128_70077336775360_0'
app/controllers/images_controller.rb:18:in `show'

这是朋友的模型,它显示了正确的方法:

class Friend < ActiveRecord::Base
  has_many:friends
  has_many :artists, :through => :publishings

  def display_name
    "#{self.first_name} #{self.second_name}"
  end
end
4

1 回答 1

1

In yesterday's question, you posted your ImagesController but the show method never sets the @artist variable.

Your stack trace here indicates that the @artist variable is nil.

But, since your model indicates that an image can have many artists, your view really should logically change to:

<% @image.artists.each do |artist| %>
  <p>
    <b>First name:</b>
    <%= artist.first_name %>
  </p>
<% end %>
于 2012-05-05T16:10:51.760 回答