So, I'm trying to add a selection for a belongs_to relationship in the User Registration form.
For example:
Here's the User model:
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
Thing model:
class Thing < ActiveRecord::Base
attr_accessible :name
has_many :user
validates_presence_of :name
validates :name, :uniqueness => { :case_sensitive => false }
end
So, I've added some code to the app/views/devise/registration/new.html.haml file:
%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"
So this all works fine, I can select the things from the select box. However, handling the submit is what I'm getting confused about. With this how it is, I'm getting a "can't mass assign protected attributes" error, which is what it should be doing.
How can I override the Devise controller to handle this? I've tried something like:
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
but I get the feeling this is not anywhere close to what I'm supposed to do. Any help would be appreciated! Thanks!