06/09/14 11:34:08
ActiveRecordで、主キーにid以外のカラムを使いたい場合、set_primary_keyでカラム名を指定すればいいはずですが、なんかエラーになります。
試しに次のようなテーブルを作り、
create table accounts (
code integer not null primary key,
name varchar(30) not null,
password varchar(30) not null
);
そしてruby script/generate scaffold accountを実行し、app/models/account.rbにset_primary_keyを追加しました。
class Account < ActiveRecord::Base
set_primary_key 'code' # 追加
end
そのあと URLリンク(localhost:3000) にブラウザでアクセスすると、/list はうまく表示されるのですが、/new だと次のようなエラーがでます。
undefined method `code_before_type_cast' for #<Account:0x22ebadc>
/usr/local/lib/ruby/gems/1.8/gems/activerecord-1.14.4/lib/active_record/base.rb:1789:in `method_missing'
/usr/local/lib/ruby/gems/1.8/gems/actionpack-1.12.5/lib/action_view/helpers/form_helper.rb:340:in `value_before_type_cast'
/usr/local/lib/ruby/gems/1.8/gems/actionpack-1.12.5/lib/action_view/helpers/form_helper.rb:253:in `to_input_field_tag'
/usr/local/lib/ruby/gems/1.8/gems/actionpack-1.12.5/lib/action_view/helpers/form_helper.rb:160:in `text_field'
#{RAILS_ROOT}/app/views/users/_form.rhtml:5:in `_run_rhtml_users__form'
#{RAILS_ROOT}/app/views/users/new.rhtml:4:in `_run_rhtml_users_new'
なんか「code_before_type_castというメソッドがない」というエラーなので、モデルに
def code_before_type_cast; code; end
を追加したらエラーはでなくなったんですけど、あまり正しい解決法には見えないので、詳しい人のアドバイスお願いします。