所以,我试图在用户注册表单中添加一个 belongs_to 关系的选择。
例如:
这是用户模型:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
# attr_accessible :title, :body
belongs_to :thing
validates_presence_of :thing
end
事物模型:
class Thing < ActiveRecord::Base
attr_accessible :name
has_many :user
validates_presence_of :name
validates :name, :uniqueness => { :case_sensitive => false }
end
因此,我在 app/views/devise/registration/new.html.haml 文件中添加了一些代码:
%h2 Sign up
= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f|
= devise_error_messages!
%div
= f.label :email
%br
= f.email_field :email, :autofocus => true
%div
= f.label :password
%br
= f.password_field :password
%div
= f.label :password_confirmation
%br
= f.password_field :password_confirmation
%div
= f.label :thing
%br
= f.select :thing, @things.map{ |r| [r.name, r.id] }
%div
= f.submit "Sign up"
= render "devise/shared/links"
所以这一切都很好,我可以从选择框中选择东西。但是,处理提交是我感到困惑的地方。就这样,我得到一个“不能批量分配受保护的属性”错误,这是它应该做的。
我怎样才能覆盖设计控制器来处理这个?我试过类似的东西:
class RegistrationsController < Devise::RegistrationsController
def new
@things = Thing.all.sort_by{|e| e[:name]}
super
end
def create
@user = User.new(params[:user][:email], params[:user][:password])
@user.thing = params[:user][:thing]
super
end
end
但我觉得这与我应该做的事情并不接近。任何帮助,将不胜感激!谢谢!