-2

I have two models: User and Role. The User attributes are:

name:string
email:string 
admin:boolean 
role_id:integer

The Role attributes are:

designer:boolean 
developer:boolean

The associations that I've set is that user belongs_to role and role has_many users. When the user signs up, I want him to choose his position (either designer or developer). However, I get the role_id as an Integer field when I want to display the positions (designer and developer) to choose from. Can anyone help me with that?

Ilya
  • 13,337
  • 5
  • 37
  • 53
  • The bit where you use: `admin:boolean`, `designer:boolean`, and `developer:boolean` really makes my eyes hurt. I suggest you re-think your design. – jvillian Apr 16 '16 at 16:05

1 Answers1

0

What you want to do is called "Nested Models".

First you have to tell the model to allow the other model like this:

# app/model/user.rb
class User < ActiveRecord::Base
  belongs_to :role
  accepts_nested_attributes_for :role
end

the next thing is in your view

#app/views/users/new.html.ham
= simple_form_for @user do |f| 
  = f.input :name
  = f.input :email
  %br
  = f.simple_fields_for :role do |role|
    = role.input :designer
    = role.input :developer
  = f.button :submit, "Send Message", :class => 'btn btn-primary btn-block'

Now last but bot least you to be able to accept the new params in the controller

class UsersController < ApplicationController
  expose(:users){User.all.order(:id)}
  expose(:user, attributes: :user_params)

  def new
    @user = User.new
    @user.role.build
  end

  def create
    if user.save
      flash[:notice] = t(:user_was_successfully_created)
      redirect_to root_path
    else
      render :new
    end
  end

  private
  def user_params
    params.require(:user).permit(
      [
        :email ,
        :name ,
        role_attributes: [
          :designer,
          :developer,
        ]
      ]
    )
  end
end

you can look at a sample app https://github.com/mzaragoza/sample_nestes_forms

I hope that this helps Happy Hacking

MZaragoza
  • 10,108
  • 9
  • 71
  • 116