item.rb
has_many :images
accepts_nested_attributes_for :images
image.rb
belongs_to :item, optional: true  #Autoriser nil pour les clés externes
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] ) #Il est nécessaire de mettre destroy et id dans le tableau lors de l'édition
end
<%= form_for @item do |f| %>
  <%= f.text.field :name %>
  <%= f.text.field :infomation %>
  <%= f.text.field :price %>
  <%= f.fields_for :image do |i| %>
    #Afficher s'il y a une image
    <%= image_tag(i.object.content) %> 
    <%= i.file_field :image %>
  <%= f.submit %>
<% end %>
c'est tout
Recommended Posts