Skip to content

Instantly share code, notes, and snippets.

@yu-smc
Last active July 8, 2018 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yu-smc/0a5713c3927a5108a07c795c32400a41 to your computer and use it in GitHub Desktop.
Save yu-smc/0a5713c3927a5108a07c795c32400a41 to your computer and use it in GitHub Desktop.
編集機能について現状わかっていること
.container.proto-new
= form_for @prototype do |f|
= f.hidden_field :user_id, value: current_user.id
.col-md-8.col-md-offset-2
%header.row.user-nav.row
.col-md-12
%h4 Title
.proto-new-title
= f.text_field :title, required: true, autofocus: true, placeholder: "Input Title"
.row
.col-md-12
%h4 Main Thumbnail
.cover-image-upload#main_image_uploader
- i = 1
= f.fields_for :captured_images, @prototype.captured_images do |image|
- if image.status == 0
%img#selected_image_0
= image.file_field :content
= image.hidden_field :status, value: "main"
= image.hidden_field :order, value: 0
- elsif image.status == 1
= image.file_field :content
= image.hidden_field :status, value: "sub"
= image.hidden_field :order, value: i
- i += 1
/ .col-md-12
/ %h4 Sub Thumbnails
/ %ul.proto-sub-list.list-group
/ - 3.times do |i|
/ %li.list-group-item.col-md-4
/ .image-upload
/ = f.fields_for :captured_images do |image|
/ %img(id='selected_image_#{i+1}')
/ = image.file_field :content
/ = image.hidden_field :status, value: "sub"
/ = image.hidden_field :order, value: i + 1
/ .row.proto-description
/ .col-md-12
/ %h4 Catch Copy
/ = f.text_field :catch_copy, require: true, placeholder: "Input Catch Copy"
/ .col-md-12
/ %h4 Concept
/ = f.text_area :concept, require: true, placeholder: "Input Concept"
/ .row.text-center.proto-btn
/ = f.submit "SAVE", id: "button", class: "btn btn-lg btn-primary btn-block"
def edit
@prototype.captured_images.find_or_initialize_by(order: 0)
3.times do |i|
@prototype.captured_images.find_or_initialize_by(order: i)
end
end
いろいろいじっていたら致命的なバグを見つけました。
メイン画像のみを選んだ場合はよいのですが、メイン画像とサブ画像1枚の合計2枚を登録した場合、
そのプロトタイプの編集時に、inputタグが1枚の画像につき2つ出現しています。
これが合計3枚だと3つ、4枚だと4つとどんどん増えてしまいます。
(これが、captured_images_attribut_16_contentとかわけのわからない数字がでてしまっていた原因です。)
これの根本的な原因ですが
fields_forは紐づくcaptured_images全てに対して展開されるため、
editアクションのviewにてfields_forが呼ばれるたびに、
選択された画像それぞれに対していちいち展開されてしまう点でした。
この問題を解消するには、ひとつのviewでfields_forを1回だけ呼んで、
その中で4枚の画像分のインプットを条件分岐で展開してあげる必要があると考えられます。
また、コントローラでは新規登録時に登録されていない分の画像のインスタンスを新規作成するとよいのではないかと思います。
上が、こんなかんじで書いたらいいんではないかというコードなのですが、いまのところstatusがundefinedというエラーが出て進みません。
もし編集機能に取り組まれるようでしたら、以上参考にしてやってみていただけると幸いです。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment