我有一个城市模型
class City < ActiveRecord::Base
belongs_to :country
end
我还使用标准的Devise gem进行用户注册和登录。现在,我希望每个用户在编辑帐户时都拥有多个国家/地区。我将额外参数(city_ids)作为数组添加到Devise User model
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 :(得分: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