Ruby on Railsを独学で勉強しております、初心者です。
今、簡単なブログサイトを勉強で開発しております。
以下のサイトを参考にしながらCarrierWaveで複数の画像を投稿する仕組みを開発しております。
https://qiita.com/sinagaki58/items/a0d59cc41c6824bb5f67
https://qiita.com/_Yasuun_/items/a7e4a2e44c3c27ec3ba2
https://qiita.com/Tommy1218/items/6349d8d860c5982771ff
コードは以下の通りです。
Post.rb(投稿) # == Schema Information # # Table name: posts # # id :integer not null, primary key # user_id :integer not null # title :string not null # content :text # status :string default("draft"), not null # created_at :datetime not null # updated_at :datetime not null # deleted_at :datetime # # Indexes # # index_posts_on_deleted_at (deleted_at) # index_posts_on_user_id (user_id) # class Post < ApplicationRecord has_many :photos, class_name: "PostPhoto", dependent: :destroy accepts_nested_attributes_for :photos end
PostPhoto.rb(投稿の写真) # == Schema Information # # Table name: post_photos # # id :integer not null, primary key # post_id :integer not null # image :string # created_at :datetime not null # updated_at :datetime not null # # Indexes # # index_post_photos_on_post_id (post_id) # class PostPhoto < ApplicationRecord belongs_to :post validates :image, presence: true mount_uploader :image, PictureUploader end
post_controller.rb def new @post = Post.new 3.times { @post.photos.build } end # 投稿の編集フォーム def edit @post = current_user.posts.find(params[:id]) @post.photos.each do |photo| photo.image.cache! end end def create @post = current_user.posts.new(post_params) if @post.save redirect_to @post, notice: "投稿しました" else render :new end end def update @post = current_user.posts.find(params[:id]) if @post.update_attributes(post_params) redirect_to @post, notice: "投稿を編集しました。" else render :edit end end private def post_params params.require(:post).permit(:title, :content, :status, photos_attributes: [:image]) end
Posts/new.html.slim, edit.html.slim = form_for(@post, html: { multipart: true }) do |form| = form.fields_for :photos do |photo| = photo.file_field :image = form.hidden_field :image_cache = form.submit "上記の内容で作成する"
上記のコードですと、複数の画像3つをアップロード出来ますが、更新するときに、画像が削除されずに追加されます。
(3枚から6枚などになります)
さらに、更新の画面やバリデーションのエラーの際、前回、新規作成の時に写真を3枚アップロード済みですが、以下のように「選択されていません」と表示されます。(DBには保存されているが、image_cacheが正確に動いていないため?)
【質問したい内容】
①更新の時は、「選択されていません」ではなく、前回アップロードしたファイルのファイル名を表示させる
②複数の画像3つを更新するときに、画像が削除されずに追加される仕様から、3つの内、更新した画像のみを新しくアップロードする
③Post(投稿)のphoto(写真)は最大で3枚にする(1〜2枚でも可)
アドバイスなどよろしくお願いいたします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。