nkuligoski February 2016

How would I display the department_name rather than the department_id?

I am learning RoR and trying to setup an association between a User model and Department model. Currently, I am able to choose a department from a dropdown field and then save it. However, when showing the user or presenting the user in a list, the department shows the id number and not the department name. I cant figure out what I am doing wrong. Any help would be greatly appreciated!

Here are the models:

class User < ActiveRecord::Base
    belongs_to :departments
end
class Department < ActiveRecord::Base
    has_many :users
end

Here are the controllers:

class UsersController < ApplicationController
    before_action :logged_in_user, only: [:edit, :update, :destroy]
    before_action :admin_user, only: [:index, :destroy]

    def new
        @user = User.new
    end

    def create
        @user = User.new(user_params)
        if @user.save
            log_in @user
            flash[:success] = "Account created!"
            redirect_to root_path
        else
            render 'new'
        end
    end

    def index
        @filterrific = initialize_filterrific(
            User,
            params[:filterrific],
            select_options: 
                {
                    sorted_by_name: User.options_for_name,
                    department_select: Department.options_for_select
                },
        ) or return

        @users = @filterrific.find.page(params[:page])

        respond_to do |format|
            format.html
            format.js
        end
    end

    def show
        @user = User.find(params[:id])
    end

    def edit
        @user = User.find(params[:id])
    end

    def update
        @user = User.find(params[:id])
        if @user.update_attributes(user_params)
            flash[:success] = "Profile successfully updated."
            redirect_to edit_user_path
        else
            render 'edit'
        end
    end

    def destroy
        User.find(params[        

Answers


Oleander February 2016

Try belongs_to :department instead of belongs_to :departments inside the User class.

Post Status

Asked in February 2016
Viewed 1,050 times
Voted 6
Answered 1 times

Search




Leave an answer