2017-02-20 2 views
1

Ich habe ein StadtmodellWie funktioniert die Mehrfachauswahl mit Devise und Rails?

class City < ActiveRecord::Base 
    belongs_to :country 
end 

Und ich standart auch Juwel für die Benutzerregistrierung und Login Entwickeln. Jetzt möchte ich, dass jeder Benutzer mehrere Länder hat, während er sein Konto bearbeitet. Ich fügte hinzu, zusätzliche Parameter (city_ids) als Array User-Modell

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 

zu ersinnen und ich änderte auch meine Vorlage mit ihm

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

zu arbeiten, aber es schreibt nicht Werte in ein Array.

Antwort

0

Fügen Sie einfach ein has_many :countries zu Benutzermodell hinzu, und fügen Sie einen entsprechenden Fremdschlüssel zu Ihrer Datenbank hinzu. Werfen Sie einen Blick Ruby on Rails Guide, finden Sie alle Informationen die Sie benötigen

Modelle

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