2017-03-04 48 views
0

在我的應用程序中,有用戶提交的評論。每個評論都有很多照片。我需要的是循環查看屬於用戶的評論,並在每個評論中顯示第一張照片。如何根據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 %> 

回答

1

在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

你想要顯示圖像嗎?或者你只是想顯示這個名字? –

相關問題