item.rb
has_many :images
accepts_nested_attributes_for :images
image.rb
belongs_to :item, optional: true #Allow foreign key nil
mount_uploader :image, ImageUploader
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] ) #When editing, it is necessary to put destroy and id in the array
end
<%= form_for @item do |f| %>
<%= f.text.field :name %>
<%= f.text.field :infomation %>
<%= f.text.field :price %>
<%= f.fields_for :image do |i| %>
#Display if there is an image
<%= image_tag(i.object.content) %>
<%= i.file_field :image %>
<%= f.submit %>
<% end %>
that's all
Recommended Posts