DataMapper で「Unknown column 'XXX_id' in 'field list'」というエラーが出たとき

たとえば Book : Author が Many to Many の関係だったとする。このとき「Book.first.authors」を実行すると、「Unknown column 'author_id' in 'field list'」というエラーが出た。

$ merb -i
irb>  Book.first.authors
 ~ SELECT `id`, `title`, `author_id` FROM `books` ORDER BY `id` LIMIT 1
 ~ Unknown column 'author_id' in 'field list' (mysql_error_code=0001)
 ....


で、この原因がさっぱり分からず苦労したんだけど、何のことはない、Author クラスの定義で「:through=>:writing」を「:thorugh=>:writing」のように typo していただけだった。

class Author
  include DataMapper::Resource
  property :id,   Serial
  property :name, String, :nullable => false
  has n, :writings
  has n, :books, :thorugh => :writings  # 正しくは :through
end


これが、「Book.first.authors」ではなく「Author.first.books」だと、「ArgumentError: Unknown property 'thorugh'」というエラーメッセージがでるので、わかりやすい。

irb> Author.first.books  
 ~ SELECT `id`, `name` FROM `authors` ORDER BY `id` LIMIT 1
ArgumentError: Unknown property 'thorugh'
        from /usr/local/lib/ruby/gems/1.8/gems/dm-core-0.9.7/lib/dm-core/query.rb:414:in `append_condition'
  ...


というわけで、DataMapper で「Unknown column 'XXX_id' in 'field list'」というエラーが出た人は、association の定義をチェックしてみるといいと思うよ。