David
David

Reputation: 957

Rails: Adding params to a Devise registration form through radio buttons

To enable different roles for users, I added some roles to the User model…

# class AddRolesToUser < ActiveRecord::Migration
   add_column :users, :host, :boolean, :default => false
   add_column :users, :company, :boolean, :default => false

and extended the registration form:

   <%= radio_button_tag(:role, "host") %>
   <%= label_tag(:role, "Host") %>
   <%= radio_button_tag(:role, "company") %>
   <%= label_tag(:role, "Company") %>

Then, in UsersController, i'd like to check for the parameter for role (e.g. "host") and mark the boolean field in the record as true:

  # users_controller.rb  
      if params[:role] == "host"
        params[:user][:host] = true
      elsif params[:role] == "company"
        params[:user][:company] = true
      end
      @user = User.new(params[:user]) …

The record won't fetch the new params, what is going wrong? thanks

EDIT

So there is no :role record, just :host and :company as boolean fields in the db. Anyone?

Upvotes: 1

Views: 1868

Answers (2)

Felix
Felix

Reputation: 694

I'm sure you've solved this by now, but I think an attr_accessor and a before_validation function would be the best solution here.

In your User model add:

attr_accessor :role
before_validation :assign_roles

def assign_roles
  self.host = (role == "host")
  self.company = (role == "company")
end

Then you can just add the fields for :user[:role] as usual in your view and no extra controller code should be needed.

Upvotes: 2

Arun Kumar Arjunan
Arun Kumar Arjunan

Reputation: 6857

Make sure that the name of the radio buttons are set to: user[host]

Instead of radio_button_tag use something like this:

  <%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
    <%= devise_error_messages! %>


    <%= f.radio_button :role, "host" %> Host
    <%= f.radio_button :role, "company" %> Company


    <%= f.submit "Sign up" %>
  <% end %>

Add the host and the company fields to the attr_accessible list on the user model like this:

attr_accessible :host, :company

Upvotes: 0

Related Questions