Last active
April 1, 2016 02:31
-
-
Save colorfulberry/ca88ba676fc236cb1d69 to your computer and use it in GitHub Desktop.
complex form how to deal
This file contains 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
#in model user.rb | |
class User < ActiveRecord::Base | |
has_one :addresses | |
end | |
#in model address.rb | |
class Address < ActiveRecod::Base | |
blongs_to :user | |
end | |
#in controller users_controller.rb | |
class UserController < ApplicationController | |
respond_to :html | |
def index | |
end | |
def new | |
@user = user.new | |
end | |
def create | |
@user = User.build(@attributes) | |
@user.save | |
respond_with @user, location: new_user_path, action: :new | |
end | |
private | |
def build_attributes | |
@attributes = params.require(:user).permit(:name | |
address { | |
:location | |
} | |
) | |
end | |
#in page new.html.erb | |
<%= form_for(setup_user(@user), url: users_path) do |f|%> | |
<%= f.label :name %> | |
<%= f.text_field :name%> | |
<%= f.fields_for :address do |ff|%> | |
<%= f.label :location %> | |
<%= f.text_field %> | |
<% end %> | |
<%= f.submit %> | |
<% end %> | |
#in helper user_helper.rb | |
module UserHelper | |
def setup_user(user) | |
user.address ||= Address.new | |
user | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment