LoginSignup
1
3

More than 3 years have passed since last update.

fields_forはこうやって使う

Posted at

手順

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 %>

以上

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3