Created
December 21, 2012 15:19
-
-
Save KitaitiMakoto/4353420 to your computer and use it in GitHub Desktop.
ActiveRecordでINNER JOINするとsaveできなくなる(解決策あり) ref: http://qiita.com/items/9c406c6a5157cdf7c651
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
require 'logger' | |
require 'active_record' | |
# テーブル定義 | |
class CreateShelves < ActiveRecord::Migration | |
def change | |
create_table :shelves | |
end | |
end | |
class CreateBooks < ActiveRecord::Migration | |
def change | |
create_table :books do |t| | |
t.integer :shelf_id | |
end | |
end | |
end | |
# モデル定義 | |
class Shelf < ActiveRecord::Base | |
has_many :books | |
end | |
class Book < ActiveRecord::Base | |
belongs_to :shelf | |
end | |
# ActiveRecordのセットアップ | |
logger = Logger.new($stderr) | |
ActiveRecord::Base.logger = logger # SQLをログに出すようにする | |
ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:' | |
# テーブル作成 | |
CreateShelves.new.change | |
CreateBooks.new.change | |
# レコード作成 | |
shelf = Shelf.create | |
shelf.books << Book.new | |
# やっと本題 | |
# これだとreadonlyになる | |
shelves = Shelf.joins(:books) | |
begin | |
shelves.first.save | |
rescue => err | |
logger.error "#{err.class} (#{err.message})" # => ActiveRecord::ReadOnlyRecord (ActiveRecord::ReadOnlyRecord) | |
end | |
# こうすればsaveできる | |
shelves = Shelf.joins(:books).readonly(false) | |
shelves.first.save # => true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment