我遇到了这个问题,我无法将图片显示为选择表单的选项。我想创建一个相册,同时选择要添加到相册的照片。
我试过" collection_check_boxes"但我无法将现有图像显示为选项。我还没有尝试创建(保存)它。
我有我的协会。 我使用Paperclip Gem作为图像。
模型:
class Album < ActiveRecord::Base
belongs_to :user
has_many :photos
end
class Photo < ActiveRecord::Base
belongs_to :owner, class_name: 'User'
belongs_to :album
has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
end
控制器:
class AlbumsController < ApplicationController
before_action :authenticate_user!, only: [:create, :new]
def index
@albums = current_user.albums
end
def new
@photos = current_user.photos.all
@album = Album.new
end
def create
@album = albums.new(album_params)
if @album.save
redirect_to user_album_path(@album)
else
redirect_to root_path
end
end
def show
@album = Album.find(params[:id])
end
def add_photo
end
private
def album_params
params.require(:album).permit(:name)
end
end
查看:
<%= form_for @album, url: user_albums_path do |f| %>
<form>
<div class="field">
<%= f.label :Name %><br />
<%= f.text_field :name %>
</div>
####################Tried this but didn't work because the image isn't a text_method
<div>
<%= collection_check_boxes(:albums, :photo_ids, current_user.photos.all, :id, image_went_here) %>
</div>
####################
<div class="actions">
<%= f.submit "Create" %>
</div>
</form>
<% end %>
答案 0 :(得分:1)
collection_check_boxes(:albums, :photo_ids,
current_user.photos.all, :id, :id) do |b|
b.label(class: "check_box") {
b.check_box(class: "check_box") + image_tag(b.object.image.url)
}
end
object
代表Photo
中代表current_user.photos.all
的块。您可能需要更改b.object.photo.url
引用以匹配您的Photo
模型。请参阅documentation中的collection_check_boxes
块的示例。
答案 1 :(得分:0)
所以我设法通过在Model中创建一个方法来填充text_method参数来解决它。
查看:
<%= collection_check_boxes(:albums, :photo_ids, @photos, :id, :myPhoto) %>
型号:
def myPhoto
ActionController::Base.helpers.image_tag("#{image.url(:thumb)}")
end
Model instanced方法允许我在collection_check_boxes中插入image_tag。