LoginSignup
0

More than 5 years have passed since last update.

railsでmongoid使う時にidがintegerになるseedsを使う時のtips

Last updated at Posted at 2016-10-13
sample_model.rb
class SampleModel
  include Mongoid::Document

  field prefecture_id, type: :Integer
  belogs_to :prefecture #idがinteger
end

# permited_params => {prefecture_id => "1"}
hoge = SampleModel.new(permited_params)
hoge.prefecture_id => 1

type: :Integerでid fieldを定義しておくと、
hashを渡した時にちゃんとIntegerになおしてくれる。
逆に定義していないと文字列の1となってしまい動かない。
field定義するという冗長になってしまうが、これが一番工数が少ない気がする。

別解として、そもそもseedsで入れる時に文字列として投入するというのもありかも。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0