Skip to content

Instantly share code, notes, and snippets.

@pftg
Last active December 14, 2015 22:48
Show Gist options
  • Save pftg/5160669 to your computer and use it in GitHub Desktop.
Save pftg/5160669 to your computer and use it in GitHub Desktop.
class BlogsController < ApplicationController
before_filter :setup
def replace
# For some reason we need only mark for destructions old article with name: "My First Article"
blog.articles.each(&:mark_for_destruction)
# params[:articles_attributes] => { name: "My First Article" }
blog.articles.build(params[:articles_attributes])
blog.save! # => raise exception!
end
private
def blog
@blog ||= Blog.find(params[:id]
end
def setup
blog.articles.create! name: 'My First Article'
end
end
class CreateBlogsAndArticles < ActiveRecord::Migration
def change
create_table :blogs do |t|
end
create_table :articles do |t|
t.string :name, null: false
t.references :blog
end
add_index :articles, [:name, :blog_id], unique: true
end
end
class Article < ActiveRecord::Base
#validates :name, uniqueness: true
end
class Blog < ActiveRecord::Base
has_many :articles, autosave: true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment