手順
1.モデルの編集
item.rb
has_many :images
accepts_nested_attributes_for :images
image.rb
belongs_to :item, optional: true #外部キーのnilを許可する
mount_uploader :image, ImageUploader
2.コントローラーの編集
item_controller.rb
def new
@item = Item.new
@item.images.build
end
def create
@item = Item.new(item_params)
redirect_to root_path
end
def edit
@item = Item.find(params[:id])
end
def update
@item = Item.find(params[:id])
@item.update(update_item_params)
redirect_to root_path
end
def item_params
params.require(:item).permit(:name, :infomation, :price, images_attributes: [:image] )
end
def update_item_params
params.require(:item).permit(:name, :infomation, :price, images_attributes: [:image, :_destroy, :id] ) #編集時はdestroyとidを配列に入れておく必要がある
end
3.ビューの編集
<%= form_for @item do |f| %>
<%= f.text.field :name %>
<%= f.text.field :infomation %>
<%= f.text.field :price %>
<%= f.fields_for :image do |i| %>
# 画像があれば表示する
<%= image_tag(i.object.content) %>
<%= i.file_field :image %>
<%= f.submit %>
<% end %>
以上