Created
June 30, 2014 04:24
-
-
Save johnathanludwig/fc540d2cc5cd06f17d1a to your computer and use it in GitHub Desktop.
Nested Form example for http://www.reddit.com/r/rails/comments/29fgf0/50_stackoverflow_anyone_got_an_answer/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%h1 New Team | |
= form_for @team do |f| | |
= f.label :name | |
= f.text_field :name | |
-# fields_for accepts a second param of the object. Use @team.players incase its an edit, otherwise build a new player | |
= f.fields_for :players, (@team.players || @team.players.build) do |players| | |
= players.label :player_name | |
= players.text_field :name | |
= f.submit "Create Team" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TeamsController < ApplicationController | |
def new | |
@team = Team.new | |
end | |
def create | |
@team = current_user.build_team(team_params) | |
if @team.save | |
redirect_to teams_path | |
else | |
render :new | |
end | |
end | |
private | |
def team_params | |
params.require(:team).permit(:name, players_attributes: [:id, :name, :role]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment