2017-02-20 3 views
1

は私が都市モデルDeviseとRailsで複数選択を使用するにはどうすればよいですか?

class City < ActiveRecord::Base 
    belongs_to :country 
end 

を持っていると私はまた、スタンダールは、ユーザー登録とログインのための宝石を考案使います。今では、各ユーザーが自分のアカウントを編集中に複数の国を持つようにしたいと考えています。私は

class ApplicationController < ActionController::Base 
    # Prevent CSRF attacks by raising an exception. 
    # For APIs, you may want to use :null_session instead. 
    protect_from_forgery with: :exception 

    before_action :configure_permitted_parameters, if: :devise_controller? 

    protected 


    def configure_permitted_parameters 
     devise_parameter_sanitizer.permit(:sign_up,  keys: [:first_name, :last_name, :email, :password, :password_confirmation]) 
     devise_parameter_sanitizer.permit(:account_update, keys: [:first_name, :last_name, :email, :password, :password_confirmation, :current_password, 
city_ids: []]) 
    end 
end 

Userモデルを考案する配列として追加のパラメータ(city_ids)を加えそして私も

<div class="field"> 
    <%= f.label :city_ids %><br /> 
    <%= f.select :city_ids, City.all.collect {|x| [x.name, x.id]}, {}, :multiple => true %> 
    </div> 

それに対応するために、テンプレートを変更しかし、それは、配列に値を書き込みません。

答えて

0

ユーザーモデルにhas_many :countriesを追加し、データベースに適切な外部キーを追加するだけです。見Ruby on Rails Guideを取る、あなたは

モデルを必要とするすべての情報を見つけることができます

class User < ActiveRecord::Base 
    has_many :countries 

    devise :database_authenticatable, :registerable, 
      :recoverable, :rememberable, :trackable, :validatable 

    attr_accessible :email, :password, :password_confirmation 
end 

class Country < ActiveRecord::Base 
    belongs_to :user 
    has_many :cities 
end 

class City < ActiveRecord::Base 
    belongs_to :country 
end 
関連する問題