[RUBY] fields_for is used like this

procedure

  1. Edit model

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
  1. Edit controller

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

  1. Edit view
<%= 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

fields_for is used like this
Maybe this is object oriented
The API looks like this!
This is the first post.
[Ruby] What is `!!` used for?
When SimpleDateFormat is garbled like ٢٠١٨١٠٠٤٠٨٣١٣٣٦٥٧
[Rails] fields_for is not displayed
This problem is soberly difficult ... (Ruby)
Why Java Vector is not used