Skip to content

Instantly share code, notes, and snippets.

@Papillard
Created July 17, 2013 14:27
Show Gist options
  • Select an option

  • Save Papillard/6021050 to your computer and use it in GitHub Desktop.

Select an option

Save Papillard/6021050 to your computer and use it in GitHub Desktop.
Use nested attributes to avoid repeating validation and save
# Using nested attribute
class Tweet < ActiveRecord::Base
has_one :location, :dependent => :destroy
accepts_nested_attributes_for :location
end
class TweetsController < ApplicationController
def new
@tweet = current_user.tweets.new(:location => Location.new) # need to instantiate the Location object
end
def create
@tweet = current_user.tweets.build(params[:tweet])
if @tweet.save
redirect_to @tweet, :notice => 'Successfully created a Tweet'
else
render :new
end
end
end
# Use in _form.html.erb
# => <%= form_for @user do |f| %>
# => <%= f.email :email %>
# => <%= f.text_field :name %>
# => <%= f.fields_for :location do |a| %>
# => <%= a.text_field :adresse %>
# => <% end %>
# => <% end %>
# Initial
# Instantiating both tweet & tweet's location, then validating/saving separately...
class Tweet < ActiveRecord::Base
has_one :location, :dependent => :destroy
end
class TweetsController < ApplicationController
def new
@tweet = current_user.tweets.build
@location = Location.new
end
def create
@tweet = current_user.tweets.build(params[:tweet])
@location = Location.new(params[:location])
if @tweet.save
@location.save
@tweet.location = @location
redirect_to @tweet, :notice => 'Successfully created a Tweet'
else
render :new
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment