2017-07-20 33 views
-1

我已經經歷了幾個問題(主要是14880100 & 2308103)並且一直無法弄清楚如何將多個圖片上傳到我的Rails模型。多張圖片上傳的問題PaperClip,嵌套Form Rails 5

這裏是我的代碼:

photo.rb

class Photo < ApplicationRecord 
attr_accessor :location_id, :name, :picture 
belongs_to :location 
has_attached_file :picture, 
       styles: { large: "", medium: "300x300#", thumb: "100x100#" }, 
       storage: :s3, 
       :s3_protocol => :https, 
       url: ":s3_domain_url", 
       default_url: "placeholder.jpg", 
       path: "/:class/:attachment/:id_partition/:style/:filename", 
       s3_region: ENV["S3_REGION"], 
       s3_credentials: Proc.new { |a| a.instance.s3_credentials } 




def s3_credentials 
{ 
    bucket: ENV['S3_BUCKET_NAME'], 
    access_key_id: ENV['S3_ACCESS_KEY_ID'], 
    secret_access_key: ENV['S3_SECRET_ACCESS_KEY'], 
} 
end 
end 

location.rb

class Location < ApplicationRecord 
    geocoded_by :address 
    after_validation :geocode 
    acts_as_votable 
    extend FriendlyId 
    friendly_id :title, use: :slugged 
    has_many :photos 
    accepts_nested_attributes_for :photos, :allow_destroy => true 
    belongs_to :user 
    has_many :comments, dependent: :destroy 


end 

的routes.rb

resources :locations do 
    resources :photos 
    resources :comments 
    member do 
     put "like" => "locations#upvote" 
     put "dislike" => "locations#downvote" 
    end 
end 

/views/locations._form.html.erb

<div class="form-group"> 
<div class="col-md-5"> 
    <%= nested_form_for @location, :html => { :multipart => true } do |f| %> 
    <%# all your building fields .... %> 

    <%= f.fields_for :photos do |photo| %> 
    <% if photo.object.new_record? %> 
     <%= photo.file_field(:picture) %> 
    <% else %> 
     <%= image_tag(photo.url(:thumb)) %> 
     <%= photo.hidden_field :_destroy %> 
     <%= photo.link_to_remove "X" %> 
    <% end %> 
    <% end %> 

    <p><%= f.link_to_add "Add photo", :photos %></p> 

<% end %></div> 

/views/locations.show.html.erb

<%= image_tag @location.photos.picture.url %> 

我的錯誤已經收到的是「未定義的方法`圖片'」。

任何提示將不勝感激。

+0

'收集您會收到積極的關係對象的數組已遍歷照片 – uzaif

回答

1

代碼@location.photos會返回一個數組,你必須遍歷它,下面是代碼:

<% @location.photos.each do |photo| %> 
    <%= image_tag(photo.picture.url)%> 
<% end %> 
在`照片
+0

我只是嘗試使用此代碼並收到以下錯誤:'SQLite3 :: SQLException:沒有這樣的列photos.location_id:SELECT「photos」。* FROM「photos」WHERE「photos」。「location_id」=?' - 我檢查了我的模式,圖片被添加爲一個字符串。 –

+0

@ pjh_1222這意味着您在'photos'表中沒有'location_id'列。您應該添加以解決該錯誤。 – Pavan

+0

@ pjh_1222 location_id是位置和照片表之間的默認外鍵。我只是閱讀回形針文檔,可以通過以下方式顯示圖像:<%= image_tag(photo.picture(:medium))%>。 – xiaocui