【发布时间】:2016-09-30 12:05:03
【问题描述】:
场景
我正在构建一个类似 AirBnB 的应用程序,但不同之处在于只有管理员可以添加新的公寓、房间、房屋等。因此,我使用 activeadmin gem 创建了一个管理面板。我现在将图像上传系统添加到 activeadmin 中,所以我使用的是回形针 gem。我有两个模型“房间”和“照片”。照片模型有一个“图像”列。房间模型有一个“listing_name”列。
room.rb(应用程序/模型)
class Room < ApplicationRecord
has_many :photos
end
photo.rb(应用/模型)
class Photo < ApplicationRecord
belongs_to :room
has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
end
如果我没有在“photo.rb (app/admin)”中放置自定义表单,我可以默认将图像与房间相关联。但是我不能上传图片!这看起来像这样:
所以我把“photo.rb (app/admin)”文件改成这样:
photo.rb(应用程序/管理员)
ActiveAdmin.register Photo do
permit_params :image
form :html => {:multipart => true} do |f|
f.inputs "Project Details" do
f.input :image, :required => false, :as => :file
end
f.actions
end
show do |ad|
attributes_table do
row :image do
image_tag(ad.image.url(:thumb))
end
end
end
end
使用此表单,我可以将图片上传到图片列,但我无法将其与房间相关联,并且编辑视图不会像显示视图那样为我提供图片预览:
问题:
如何在管理员编辑视图中预览图像?
如何通过选择房间的 listing_name 来构建一个表单以将图像与房间相关联?
类似这样的:
提前感谢您的帮助。
【问题讨论】:
-
我建议您在房间编辑/创建表单上上传图片,而不是单独添加和链接,您可以使用nested_attributes_for 来完成此操作。
标签: ruby-on-rails forms paperclip activeadmin