【问题标题】:Issues with multiple image uploads PaperClip, Nested Form Rails 5多个图像上传的问题 PaperClip,嵌套表单 Rails 5
【发布时间】:2017-07-20 13:26:16
【问题描述】:

我已经解决了几个问题(主要是 148801002308103),但无法弄清楚如何将多个图像上传到我的 Rails 模型。

这是我的代码:

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 %>

我收到的错误是“未定义的方法‘图片’”。

任何提示将不胜感激。

【问题讨论】:

  • photos 集合中,您将收到您已迭代照片的活动关系对象数组

标签: ruby-on-rails ruby paperclip


【解决方案1】:

代码@location.photos会返回一个数组,你必须遍历它,代码如下:

<% @location.photos.each do |photo| %>
  <%= image_tag(photo.picture.url)%>
<% end %>

【讨论】:

  • 我刚刚尝试使用此代码并收到以下错误:'SQLite3::SQLException: no such column photos.location_id: SELECT "photos".* FROM "photos" WHERE "photos"."location_id “=?” - 我检查了我的架构,图片被添加为字符串。
  • @pjh_1222 这意味着您在photos 表中没有location_id 列。您应该添加以解决错误。
  • @pjh_1222 location_id 是位置和照片表之间的默认外键。我刚刚阅读了回形针文档,您可以通过以下方式显示图像:.
  • @Pavan 谢谢你的帮助。我在照片中添加了该列,没有更多错误。但是,我在创建位置时上传的图像都没有出现在显示页面中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多