2016-05-27 4 views
0

私はこれを2時間続けていますが、これが起こっている理由や何らかの理由が見つからないままです。Railsがselect文からActiveRecordに "0"を渡すのはなぜですか?

ActiveModel::StrictValidationFailed in CoursesController#create 
Province 0 is not included in the list 

I:私のモデルで

私は私がフォームを送信するとき、私はこのエラーを取得する

= form_for @course, url: teach_path do |f| 
    = f.select :province, options_for_select(['Alberta','British Columbia','Manitoba','New Brunswick','Newfoundland and Labrador','Nova Scotia','Ontario','Prince Edward Island','Quebec','Saskatchewan'], "#{@course.province.to_s}"), {include_blank: "Choose your Province"}, {required: :required} 
    = f.submit 

しかし、このselect文を持っている私の見解では

models/course.rb 

class Course < ActiveRecord::Base 
    validates! :province, inclusion: { :in => ['Alberta','British Columbia','Manitoba','New Brunswick','Newfoundland and Labrador','Nova Scotia','Ontario','Prince Edward Island','Quebec','Saskatchewan', 'Province'], message: "%{value} is not included in the list" } 
end 

を持っていますアクティブなレコードモデルで独自のメソッドを定義しようとしました

def includes_province 
    unless ['Alberta','British Columbia','Manitoba','New Brunswick','Newfoundland and Labrador','Nova Scotia','Ontario','Prince Edward Island','Quebec','Saskatchewan', 'Province'].include?(province.to_s) 
    errors.add(:base, "There is no #{province} in the list") 
    end 
end 

それはちょうど

There is no 0 in the list 

を返すのはなぜ省は常に0どんなですか?私は、ログをチェックして、それが示しています

Processing by CoursesController#create as HTML 
    Parameters: {"utf8"=>"✓", "authenticity_token"=>"***", "course"=>{"province"=>"Manitoba"}, "commit"=>"submit"} 
+1

schema.rbにある都道府県のフィールドタイプは何ですか – DMH

+0

州はテーブルに整数型のようですか? – Thorin

+0

私はそれがあなたが探しているものだと思います:http://stackoverflow.com/questions/6668302/rails-select-in-form-returns-index-i-want-to-send-the-text –

答えて

0

は確かとして@spickermannあなたの州のフィールドがDB内の整数ではないことを確認言います。 rails_app/db/migrateフォルダにCourseテーブル(CreateCoursesのようなもの)を作成するマイグレーションを確認するか、単にrails_app/db/folderのschema.rbファイルをチェックしてください。そう、あなたの列がintergerがある場合、それは

t.integer :province 

を言うかどうかを確認し、それを文字列(任意の文字列)を割り当てることにより、実際の整数値に0を設定します。 は、お使いのOSのコマンドラインで「コンソールレール」の呼び出し(または「レールC」)を試してみて、あなたが代わりにそれが必要i.integerのt.stringする列の型を変更すると、その後

c = Course.take # takes random course from db and loads it to c var 
c.province = "Manitoba" # assign string value to the field - like it happens in form 
c.province # will actually print 0 ! 

を入力し、同じものを複製するには作業。

関連する問題