【问题标题】:How to create an association between two models with form choice field using Active Admin, Paperclip in Rails 5.0.1如何在 Rails 5.0.1 中使用 Active Admin、Paperclip 创建具有表单选择字段的两个模型之间的关联
【发布时间】: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

使用此表单,我可以将图片上传到图片列,但我无法将其与房间相关联,并且编辑视图不会像显示视图那样为我提供图片预览:

问题:

  1. 如何在管理员编辑视图中预览图像?

  2. 如何通过选择房间的 listing_name 来构建一个表单以将图像与房间相关联?

类似这样的:

提前感谢您的帮助。

【问题讨论】:

  • 我建议您在房间编辑/创建表单上上传图片,而不是单独添加和链接,您可以使用nested_attributes_for 来完成此操作。

标签: ruby-on-rails forms paperclip activeadmin


【解决方案1】:

尝试https://github.com/gregbell/active_admin/issues/599,然后 Macfanatics 回答。它描述了设置多态关联以及如何在 activeadmin 中使用它。它对我帮助很大。

【讨论】:

    【解决方案2】:

    解决方案:

    photo.rb

    ...
       show do |image|
          attributes_table do
             row :image do
                photo.image? ? image_tag(photo.image.url, height: '100') : content_tag(:span, "No photo yet")
             end
             row :room_id do
                photo.room ? photo.room.listing_name : ""
             end
          end
          active_admin_comments
       end
    
        form :html => { :enctype => "multipart/form-data" } do |f|
          f.inputs do
             f.input :image, hint: f.photo.image? ? image_tag(f.photo.image.url, height: '100') : content_tag(:span, "Upload JPG/PNG/GIF image")
          end
          f.inputs do
            f.collection_select :room_id, Room.all,:id,:listing_name
          end
          f.actions
       end 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多