Skip to content

Instantly share code, notes, and snippets.

@BenEddy
Created November 5, 2014 05:54
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 BenEddy/7da991aa47d36743646a to your computer and use it in GitHub Desktop.
Save BenEddy/7da991aa47d36743646a to your computer and use it in GitHub Desktop.
class User < ActiveRecord::Base
has_many :comments
accepts_nested_attributes_for :comments
end
class Comment < ActiveRecord::Base
belongs_to :user
end
u = User.new
# create a new comment via nested attributes
u.update comments_attributes: [{body: "hi"}]
# => true
# update the comment via nested attributes
u.update comments_attributes: [{id: 1, body: "hi"}]
# => true
class Comment < ActiveRecord::Base
belongs_to :user
# add some validation which fails
validates :body, numericality: true
end
# update the comment via nested attributes
u.update comments_attributes: [{id: 1, body: "hi"}]
# => true
# It saved? But our comment is invalid...
# We didn't change the comment, so Rails decides we don't need to run validations
# update the comment via nested attributes
u.update comments_attributes: [{id: 1, body: "updated"}]
# => false
# This is the behavior I would expect in both cases
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment