前提・実現したいこと
collection_select を使ってTeacher1人につき二つ以上の都道府県を登録できるようにしたいのですが、色々試した結果方法がわかりません。
該当のソースコード
prefecture.rb
class Prefecture < ApplicationRecord has_many :cities has_many :teachers_prefectures, foreign_key: 'prefecture_id' has_many :teachers, through: :teachers_prefectures end
teacher.rb
class Teacher < ApplicationRecord has_many :teachers_prefectures, foreign_key: 'teacher_id' has_many :prefectures, through: :teachers_prefectures end
teachers_prefecture.rb
class TeachersPrefecture < ApplicationRecord belongs_to :teacher belongs_to :prefecture end
このように多対多の関連付けをしています。
new.html.erb
<div clas = "field"> <%= f.label :"指導可能都道府県1" %> <%= f.collection_select :prefecture_ids, Prefecture.all, :id, :name %> </div> <div clas = "field"> <%= f.label :"指導可能都道府県2" %> <%= f.collection_select :prefecture_ids, Prefecture.all, :id, :name %> </div> <div clas = "field"> <%= f.label :"指導可能都道府県3" %> <%= f.collection_select :prefecture_ids, Prefecture.all, :id, :name %> </div>
teacher_controller.rb
class TeachersController < ApplicationController def new @teacher = Teacher.new @teacher.teachers_prefectures.build end def create @teacher = Teacher.new(teacher_params) if @teacher.save redirect_to teachers_url else render 'new' end end private def teacher_params params.require(:teacher).permit(prefecture_ids:[]) end end
このように記述しています。間違っているのはわかるのですが、どこがどのように間違っているか全くわからないので教えていただければたかります。ruby on rails もほぼ初心者で、この投稿も初めてなので、わかりにくい点や失礼な点があるかもしれませんがよろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/03/30 14:09
2019/04/05 04:16
2019/04/11 12:07