首先为@andrea +1 Transactions - 我不知道的很酷的东西
但最简单的方法是使用 accepts_nested_attributes_for method 作为模型。
让我们举个例子。我们有两个模型:Post title:string 和 Comment body:string post:references
让我们看看模型:
class Post < ActiveRecord::Base
has_many :comments
validates :title, :presence => true
accepts_nested_attributes_for :comments # this is our hero
end
class Comment < ActiveRecord::Base
belongs_to :post
validates :body, :presence => true
end
你看:我们在这里得到了一些验证。所以我们去rails console做一些测试:
post = Post.new
post.save
#=> false
post.errors
#=> #<OrderedHash {:title=>["can't be blank"]}>
post.title = "My post title"
# now the interesting: adding association
# one comment is ok and second with __empty__ body
post.comments_attributes = [{:body => "My cooment"}, {:body => nil}]
post.save
#=> false
post.errors
#=> #<OrderedHash {:"comments.body"=>["can't be blank"]}>
# Cool! everything works fine
# let's now cleean our comments and add some new valid
post.comments.destroy_all
post.comments_attributes = [{:body => "first comment"}, {:body => "second comment"}]
post.save
#=> true
太棒了!一切正常。
现在让我们用 update 做同样的事情:
post = Post.last
post.comments.count # We have got already two comments with ID:1 and ID:2
#=> 2
# Lets change first comment's body
post.comments_attributes = [{:id => 1, :body => "Changed body"}] # second comment isn't changed
post.save
#=> true
# Now let's check validation
post.comments_attributes => [{:id => 1, :body => nil}]
post.save
#=> false
post.errors
#=> #<OrderedHash {:"comments.body"=>["can't be blank"]}>
这行得通!
那么你怎么能使用它。在你的模型中以同样的方式,在像普通表单一样的视图中,但使用 fields_for tag 进行关联。您还可以使用非常深的嵌套来关联验证,它会完美运行。