前提・実現したいこと
railsでwebアプリを作成中です。
住所登録form内の「都道府県」を、別のmodel(prefecture)とマイグレーションファイルを作成し関連付けを行い、一覧ページにて都道府県でタグ検索したいと考えています。
DBの関連付けは中間テーブルを用意して行いました。
modelで関連付けを行い、form内でcollection_selectで都道府県は選べるようにしましたが、都道府県はdbに保存はされていませんでした。
model,controller,formの記述を確認したのですが、原因がわからなかったため、質問させていただきます。
該当のソースコード
view
<!--フォーム--> <%= form_for @shop do |f| %> <div class="form-group row"> <%= f.label :name, '店舗名', class:'col-md-3 col-form-label' %> <%= f.text_field :name, class:'form-control' %> </div> <div class="form-group row"> <%= f.label :telephon, "電話番号",class:'col-md-3 col-form-label'%> <%= f.text_field :telephon,class:'form-control'%> </div> <div class="form-group row"> <%= f.label :seats, "席数",class:'col-md-3 col-form-label' %> <%= f.text_field :seats,class:'form-control' %> </div> <!--住所--> <fieldset class="form-group form-group-inline"> <div class="row"> <legend class="col-form-label col-md-3"> 住所 </legend> <div class="form-check form-check-inline"> <%= f.label :postcode, "郵便番号" %> <%= f.number_field :postcode %> <%= f.label :prefecture_id, "県" %> <%= f.collection_select :prefecture_ids, Prefecture.all, :id, :name, { prompt: "選択してください" } %> <%= f.label :address_city, "市" %> <%= f.text_field :address_city %> <%= f.label :address_street, "町村" %> <%= f.text_field :address_street %> <%= f.label :address_building, "建物番地" %> <%= f.text_field :address_building %> </div> </div> </fieldset> <% end %>
controller
def new @shop = Shop.new end private def shop_params params.require(:shop).permit(prefecture_ids: []) end
model
class Prefecture < ApplicationRecord has_many :shop_prefecture_relations, dependent: :delete_all has_many :shops, through: :shop_prefecture_relations end
model
class ShopPrefectureRelation < ApplicationRecord belongs_to :shop belongs_to :prefecture end
model
class Shop < ApplicationRecord has_many :shop_prefecture_relations, dependent: :delete_all has_many :prefectures, through: :shop_prefecture_relations
migrate
class CreatePrefectures < ActiveRecord::Migration[5.2] def change create_table :prefectures do |t| t.string :name, null: false t.timestamps end end end
migrate
class CreateShopPrefectureRelations < ActiveRecord::Migration[5.2] def change create_table :shop_prefecture_relations do |t| t.references :shop, foreign_key: true t.references :prefecture, foreign_key: true t.timestamps end end end
まだ回答がついていません
会員登録して回答してみよう