Ich habe dieses Problem, wo ich meine Bilder nicht als Optionen für ein Formular auswählen kann. Ich möchte ein Fotoalbum erstellen und gleichzeitig Fotos auswählen, die dem Album hinzugefügt werden sollen.Ruby on Rails Anzeige Bild als Kontrollkästchen in einem Formular
Ich habe versucht "collection_check_boxes", aber ich kann nicht die vorhandenen Bilder als Optionen angezeigt werden. Und ich habe noch nicht versucht, es zu erstellen (speichern).
Ich habe meine Assoziationen. Ich benutze Paperclip Gem für das Bild.
Modelle:
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
Controller:
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
Aufrufe:
<%= 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 %>
Hey danke für die Antwort. Ich habe Ihren Vorschlag ausprobiert, aber leider hatte ich Probleme, das Bild immer noch anzuzeigen. Es sagt immer wieder, dass das Objekt, das ich benutzt habe, nicht definiert ist. Ich habe es aber auf andere Weise gelöst. –