Created
September 10, 2009 09:18
-
-
Save raecoo/184436 to your computer and use it in GitHub Desktop.
many methods to validate association model in rails
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
# validation method 1 | |
if @user.save && @order.save && @city.save | |
... | |
else | |
... | |
end | |
# validation method 2 | |
if @user.valid? && @order.valid? && @city.valid? | |
@user.save | |
@order.save | |
@city.save | |
... | |
else | |
... | |
end | |
# validation method 3 | |
@city = City.new params[:city] | |
@user = User.new params[:user] | |
@user.city = @city | |
@order = Order.new params[:order] | |
@order.user = @user | |
unless [@user, @city, @order].map(&:valid?).include?(false) | |
@user.save | |
@city.save | |
@order.save | |
... | |
else | |
... | |
end | |
# another version | |
if [@user, @city, @order].select{|model| model.valid? == false}.empty? | |
... | |
else | |
... | |
end | |
# validation method 4 | |
@city = City.new params[:city] | |
@user = @city.users.build params[:user] | |
@order = @user.orders.build params[:order] | |
@city.save ? redirect_to "/main/new" : render :action => "new" | |
# validation method 5 | |
# define global AR Transaction filter | |
class TransactionFilter | |
def filter(controller) | |
return yield if controller.request.get? | |
ActiveRecord::Base.transaction do | |
yield | |
end | |
end | |
end | |
# define filter | |
around_filter :transaction_filter | |
def transaction_filter(&block) | |
TransactionFilter.new.filter(self, &block) | |
end | |
# validation method 6 | |
class Topic < ActiveRecord::Base | |
attr_accessor :body | |
has_many :posts, :autosave => true | |
validates_presence_of :title | |
end | |
class Post < ActiveRecord::Base | |
belongs_to :topic | |
validates_presence_of :body | |
end | |
def create | |
@topic = Topic.new(params[:topic]) | |
@topic.posts << Post.new(:body => params[:topic][:body]) | |
@topic.save ? redirect_to(@topic) : render :action => :new | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment