Skip to content

Instantly share code, notes, and snippets.

@thanhcuong1990
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thanhcuong1990/e8521731280f4507955d to your computer and use it in GitHub Desktop.
Save thanhcuong1990/e8521731280f4507955d to your computer and use it in GitHub Desktop.
Nested attributes example 1
# /app/models/user.rb
class User < ActiveRecord::Base
has_one :account_setting, :dependent => :destroy
end
# /app/controllers/users_controller.rb
class UsersController < ApplicationController
def create
@user = User.new(params[:user])
@account_setting = AccountSetting.new(params[:account_setting])
if @user.save
@account_setting.user = @user
@account_setting.save
redirect_to(@user, :notice => 'User was successfully created.')
else
render :action => "new"
end
end
end
# /app/views/users/edit.html.erb
<%= fields_for :account_setting do |a| %>
<div class="field">
<%= a.label :public_email %><br />
<%= a.check_box :public_email %>
</div>
<div class="field">
<%= a.label :show_media %><br />
<%= a.check_box :show_media %>
</div>
<div class="field">
<%= a.label :protect_posts %><br />
<%= a.check_box :protect_posts %>
</div>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment