12
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Rails 4.x] Simple_form で、複数モデルを使って、複数のテーブルに複数のレコードを挿入する方法

Last updated at Posted at 2014-10-28

前置き

備忘録的なメモです。ミスもあるかと思います。
また、小汚いコードになってしまった上に、あんまりきれいなやり方には思えないので、別の方法があったらそちらを優先した方がいいと思います。

概要

friendフォームから、friend_controller.rbを伝って、FriendsテーブルとFriendMemosテーブルにデータを入れたい。
friendフォームでは、友達の基本情報と友達の紹介や説明などの情報を入力してもらう。

(1つのフォームでいっぺんにデータをやりとりするより、複数に分けた方が、ユーザーからしても、システム的にも好ましいんじゃないかとも思うが、とりあえず。)

form

form
<%= simple_form_for([@user,@friend] :url => user_friend_path,:html => {:id => 'user_form', :multiport => true}) do |f| %>
  <%= f.error_notification %>
 ・
 ・
  <!-- jsかなんかで以下のフォームの表示非表示制御などを入れた方がいい -->
  <% @friends_memos.each do |fms| %>
    <div class="friend-memos-form">
      <%= simple_fields_for "friend_memos[]", fms do |fm|  %>
        <%= fm.association :certainty, required: false, input_html: { class: "form-control" }, label: "hoge" %>
        <%= fm.input :kind, collection: [['好きなもの','likes'],['好きな映画','movie']・・・・]]required: false, input_html: { class: "form-control" }, label: "fuga" %>
        <%= fm.input :memo %>
      <% end %>
    </div>
  <% end %>
 ・
 ・
<% end %>

controller

def new
  @friend = Friend.new
  @friend_memos = Array.new(5) { @friend.friend_memos.build }
end

def create
  @friend = Friend.create(friend_params)
  for f in params[:friend]
    # 書き込みがなかった場合にはどうするかなどの制御を入れて
      @friend_memos = FriendMemos.create(
                                friend_id: @friend.id,
                                certainty: f["certainty"],
                                progress: f["progress"],
                                memo: f["memo"]
                                )
  end

  private
  def friend_params
    params.require(:friend).permit(・・・・)
  end
  def friend_memos_params
    params.require(:friend_memos).permit(・・・・)
  end
end


参考

http://stackoverflow.com/questions/15991243/simple-form-label-to-be-column-value
http://stackoverflow.com/questions/4383391/rails-3-edit-multiple-records-in-a-single-form
http://npb.somewhatgood.com/blog/archives/901

12
10
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
12
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?