如何根据id选择第一张图像并显示在(显示)视图中?

问题描述:

在我的应用程序中,有用户提交的评论。每个评论都有很多照片。我需要的是循环查看属于用户的评论,并在每个评论中显示第一张照片。如何根据id选择第一张图像并显示在(显示)视图中?

我感谢你的帮助:)

这工作在控制台,我能够回到正确的照片。在审查1有3张照片,这正确地返回第一个。

Photo.where(:review_id => 1).pluck(:file_name).first 

现在我试图将它们显示在users/show.html.erb文件中,因此它不起作用。

<% @user.reviews.each do |review| %> 
<%= image_tag review.firstphoto.url %> 
<% end %> 

我还试图限定的方法得到的第一张照片中reviews_controller.rb

def firstphoto 
@photo = Photo.where(:review_id => @review_id).pluck(:file_name).first 
end 

这里有关联

class Review < ActiveRecord::Base 
belongs_to :brand 
belongs_to :user 
has_many :photos 

class Photo < ActiveRecord::Base 
belongs_to :review 

class User < ActiveRecord::Base 
has_many :reviews 

的照片存储在S3,并使用该架构存储在数据库中。

create_table "photos", force: :cascade do |t| 
t.datetime "created_at", null: false 
t.datetime "updated_at", null: false 
t.text  "file_name" 
t.integer "review_id" 

为了说明这些照片,使用此代码正确显示在reviews/show.html.erb中。

<% @review.photos.each do |photo| %> 
<%= image_tag photo.file_name.url %> 
<% end %> 

在users_controller.rb表演动作

@reviews = current_user.reviews 

然后在用户/ show.html.erb文件

<% @reviews.each do |review| %> 
    <%= image_tag review.first_photo %> 
<% end %> 

现在创建review.rb模型的实例方法如下代码。

def first_photo 
    photos.first.file_name.url if photos.first.present? 
end 

这会做你想做的。让我知道如果你仍然面临这个问题。

+0

我没有'图像',所以我不能使用photos.first.image.url。 我确实尝试了photos.first.file_name.url,但它返回了未定义的方法 – Joshua

+0

您能否让我知道您在哪个字段存储了您的图像。所以我可以帮助你。如果您有问题找到图像字段。让我知道你存储图像的代码。我会自己找出来的。 –

+0

你想要显示图像吗?或者你只是想显示这个名字? –