如何将附加到评论的图像放入歌曲中的index.html.erb?

时间:2017-10-19 01:28:19

标签: ruby-on-rails ruby ruby-on-rails-4

歌曲中有评论,它有一对多关系,每条评论都有一张图片, 我想在歌曲列表中放置每个具有最佳数量的图像。

<% @songs.each do |song| %>
      <div class="col-md-4 col-sm-6 portfolio-item">
        <a class="portfolio-link" data-toggle="modal" href="#portfolioModal1">
          <div class="portfolio-hover">
            <div class="portfolio-hover-content">
              <i class="fa fa-plus fa-3x"></i>
            </div>
          </div>
          <%= image_tag song.comments.image.url(:medium).order(:cached_votes_up => :desc).limit(1) %>
          <img class="img-fluid" src="/assets/noimage.jpg" alt="">
        </a>
        <div class="portfolio-caption">

但是我收到了一个错误:

enter image description here

我不知道为什么图像会变成NoMethodError。 此外,应该进行歌曲和评论之间的关联。

class Song < ActiveRecord::Base
acts_as_votable
belongs_to :user
has_many :comments, :dependent => :destroy
end

class Comment < ActiveRecord::Base
acts_as_votable
belongs_to :user
belongs_to :song

has_attached_file :image, styles: { :medium => "400x400#", :thumb => 
"180x180#" }, :default_url => "noimage.jpg"
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
end

我该如何解决这个问题?

NoMethodError in Songs#index
undefined method `each' for nil:NilClass
<% @songs.each do |song| %>
      <div class="col-md-4 col-sm-6 portfolio-item">

         <%= link_to like_song_path(song), method: :put, class: "portfolio-link" do %>
          <div class="portfolio-hover">
            <div class="portfolio-hover-content">
              <i class="fa fa-plus fa-3x">
              </i>
            </div>
          </div>

         <% @comments.each do |comment| %>
         <%= image_tag song.comments.order(:cached_votes_up => :desc).limit(1).first.image.url(:medium) %>
         <% end %>

          <% end %>

song.controoler↓

 before_action :set_song, only: [:show, :edit, :update, :destroy]
 before_action :authenticate_user!, except: [:index, :show]
 # GET /songs
 # GET /songs.json
 def index
 if params[:user_id]
  @user = User.find(params[:user_id])
  @songs = @user.songs.order(:cached_votes_up => :desc)
 else
  @songs = Song.all.order(:cached_votes_up => :desc)
 end
 end



private
# Use callbacks to share common setup or constraints between actions.
def set_song
  @song = Song.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def song_params
  params.require(:song).permit(:title, :body, :get_upvotes)
end

我认为问题是@comments没有在索引操作中定义。

我知道我没有在索引操作中定义@comment,但我不确定如何编码。

2 个答案:

答案 0 :(得分:0)

您看到的例外情况是由于在评论集合上调用#limit(1)而不是单个评论对象。即使<%= image_tag song.comments.order(:cached_votes_up => :desc).limit(1).first.image.url(:medium) %> 正在应用于查询,返回的结果仍然是一个集合。要修复错误,您可以将现有查询修改为以下内容:

{{1}}

希望这有帮助!

答案 1 :(得分:0)

你可以这样做

<%= image_tag song.comments.order(:cached_votes_up => :desc).limit(1).first.image.url(:medium) if song.comments.order(:cached_votes_up => :desc).limit(1).present? %>

我希望这对你有所帮助。