2017-02-20 46 views
1

我有一個城市模型如何使用Devise和Rails進行多個選擇?

class City < ActiveRecord::Base 
    belongs_to :country 
end 

而且我也使用非標準設計的用戶註冊和登錄的寶石。現在我希望每個用戶在編輯帳戶時都有多個國家/地區。我添加額外的參數(city_ids)作爲數組來設計用戶模型

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 

而且我也改變了我的模板,它

<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 
相關問題