Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save wada811/e50eb9cfb5de13bf880e to your computer and use it in GitHub Desktop.
Save wada811/e50eb9cfb5de13bf880e to your computer and use it in GitHub Desktop.
[Rails] nested_form で1対多のフォームを実装する

Rails4のMass Assignment脆弱性対策のStrong Parametersについて | DevAchieve

def users_children_params
  params.fetch(:user, {}).permit(
    :children_attributes => [:id, :birthday, :_destroy],
  )
end
has_many :children, :dependent => :destroy

accepts_nested_attributes_for :children
belongs_to :user
<%= nested_form_for(@user) do |f| %>
  <%= f.fields_for :children do |child| %>
    <div>
      <%= child.label :birthday %>
      <%= child.text_field :birthday %>
      <%= child.link_to_remove "Remove this" %>
    </div>
  <% end %>
  <p><%= f.link_to_add "Add a Child", :children %></p>
  <div><%= f.submit "Save" %></div>
<% end %>

一対多でユーザーが子供を持つ場合に子供がゼロ人でも良い場合は上記でOK 1人は必ず持っていないといけない場合に フォームを1つはデフォルトで表示しておいて追加で表示させる方法がわからない。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment