Created
July 17, 2013 14:27
-
-
Save Papillard/6021050 to your computer and use it in GitHub Desktop.
Use nested attributes to avoid repeating validation and save
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
| # 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 %> |
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
| # 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