我如何显示department_name而不是department_id?

时间:2016-02-08 21:51:29

标签: ruby-on-rails ruby

我正在学习RoR并尝试在User模型和Department模型之间建立关联。目前,我可以从下拉字段中选择一个部门,然后保存。但是,在显示用户或在列表中显示用户时,部门会显示ID号而不是部门名称。我无法弄清楚我做错了什么。任何帮助将不胜感激!

以下是模型:

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

以下是控制器:

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[:id]).destroy
        flash[:success] = "User deleted."
        redirect_to users_url
    end

    private

        def user_params
            params.require(:user).permit(:name, :email, :work_phone, :department, :cell_phone, :password, :password_confirmation)
        end

        # Before filters
        def logged_in_user
            unless logged_in?
                store_location
                flash[:danger] = "Please log in first."
                redirect_to login_url
            end
        end

        # Confirms an admin user.
        def admin_user
            redirect_to(root_url) unless current_user.admin?
        end

end

class DepartmentsController < ApplicationController
    def create
        @department = Department.new(department_params)
        if @department.save
            redirect_to(:action => 'index')
        else
            render 'new'
        end
    end

    def index
        @department = Department.all
    end

    def show
        @department = Department.find(params[:id])
    end

    def edit
        @department = Department.find(params[:id])
    end

    def update
        @department = Department.find(params[:id])
    end

    def delete
        @department = Department.find(params[:id])
    end

    def destroy
        Department.find(params[:id]).destroy
        redirect_to(:action => 'index')
    end

    private

        def department_params
            params.require(:department).permit(:name, :department_ids => [])
        end

end

我的编辑HTML:

<% provide(:title, "Edit user") %>

<h1>Update your profile</h1>

<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <%= form_for(@user) do |f| %>
            <%= f.label :name, class: 'form-spacing' %>
            <div class="input-group">
                <%= f.text_field :name, class: 'form-control' %>
                <span class="input-group-addon" id="basic-addon2">
                    <span class="glyphicon glyphicon-user"></span>
                </span>
            </div>

            <%= f.label :email, class: 'form-spacing' %>
            <div class="input-group">
                <%= f.email_field :email, class: 'form-control' %>
                <span class="input-group-addon" id="basic-addon2">
                    <span class="glyphicon glyphicon-envelope"></span>
                </span>
            </div>

            <%= f.label :work_phone, class: 'form-spacing' %>
            <div class="input-group">
                <%= f.text_field :work_phone, class: 'form-control' %>
                <span class="input-group-addon" id="basic-addon2">
                    <span class="glyphicon glyphicon-phone"></span>
                </span>
            </div>

            <%= f.label :cell_phone, class: 'form-spacing' %>
            <div class="input-group">
                <%= f.text_field :cell_phone, class: 'form-control' %>
                <span class="input-group-addon" id="basic-addon2">
                    <span class="glyphicon glyphicon-phone"></span>
                </span>
            </div>

            <%= f.label :department, class: 'form-spacing' %>
            <div class="input-group">
                <div class="input-group-btn">
                    <%= f.collection_select :department, Department.order(:name), :id, :name, {}, {class: 'form-control'} %>
                </div>
            </div>

            <%= f.label :password, class: 'form-spacing' %>
            <%= f.password_field :password, class: 'form-control' %>

            <%= f.label :password_confirmation, "Confirmation", class: 'form-spacing' %>
            <%= f.password_field :password_confirmation, class: 'form-control' %>

            <%= f.submit "Save changes", class: "btn btn-primary center-block btn-margin" %>
        <% end %>
    </div>
</div>

列出HTML:

<div class="row well well-sm">
    <div class="col-lg-6">
        <div id="filterrific_results">
            <div>
                <%= page_entries_info users %><%= render_filterrific_spinner %>
            </div>
        </div>
    </div>
    <div class="pull-right">
        <%= link_to 'Reset', reset_filterrific_url, class: "btn btn-default" %>
    </div>
</div>

<table class="table table-condensed">
    <tr>
        <th>Profile</th>
        <th>Name</th>
        <th>Email</th>
        <th>Work #</th>
        <th>Cell #</th>
        <th>Department</th>
    </tr>
    <% users.each do |user| %>
        <tr>
            <td><%= link_to user_path(user.id), class: "btn btn-xs" do %>
                <i class="glyphicon glyphicon-user"></i>
                <% end %>
            </td>
            <td><%= link_to(user.name, edit_user_path(user)) %></td>
            <td><%= user.email %></td>
            <td><%= user.work_phone %></td>
            <td><%= user.cell_phone %></td>
            <td><%= user.department %></td>
        </tr>
    <% end %>
    </table>

<%= will_paginate users %>

以下是我尝试使用user.department.name时收到的跟踪:

NoMethodError in Users#index
Showing C:/Users/ngkuligoski/Desktop/workspace/tgna_app/app/views/users/_list.html.erb where line #33 raised:

undefined method `name' for "30":String
Trace of template inclusion: app/views/users/index.html.erb

Rails.root: C:/Users/ngkuligoski/Desktop/workspace/tgna_app

Application Trace | Framework Trace | Full Trace
app/views/users/_list.html.erb:33:in `block in _app_views_users__list_html_erb___81315648_98180820'
app/views/users/_list.html.erb:23:in `_app_views_users__list_html_erb___81315648_98180820'
app/views/users/index.html.erb:39:in `_app_views_users_index_html_erb___1258199830_74038920'
app/controllers/users_controller.rb:33:in `index'

当切换belongs_to:department而不是belongs_to:departments时,我收到以下错误:

ActiveRecord::AssociationTypeMismatch in UsersController#update
Department(#70215520847100) expected, got String(#70215501520980)

Extracted source (around line #49):

47: def update
48:     @user = User.find(params[:id])
49:     if @user.update_attributes(user_params)
50:         flash[:success] = "Profile successfully updated."
51:         redirect_to edit_user_path
52:     else

Rails.root: /Users/nkuligoski/Desktop/tgna_app

Application Trace | Framework Trace | Full Trace
app/controllers/users_controller.rb:49:in `update'

从user.params中删除:部门后,我现在在提交表单时没有收到错误。但是,我现在在列表视图中收到以下错误,并且我从SQL获得了“未经许可的参数:部门”错误反馈。

NoMethodError in Users#index
Showing /Users/nkuligoski/Desktop/tgna_app/app/views/users/_list.html.erb where line #33 raised:

undefined method `name' for nil:NilClass
Extracted source (around line #33):

31            <td><%= user.work_phone %></td>
32            <td><%= user.cell_phone %></td>
33            <td><%= user.department.name %></td>
34        </tr>
35    <% end %>
36    </table>

Trace of template inclusion: app/views/users/index.html.erb

Rails.root: /Users/nkuligoski/Desktop/tgna_app

Application Trace | Framework Trace | Full Trace
app/views/users/_list.html.erb:33:in `block in _app_views_users__list_html_erb__2838324632886829267_70215593187400'
app/views/users/_list.html.erb:23:in `_app_views_users__list_html_erb__2838324632886829267_70215593187400'
app/views/users/index.html.erb:39:in `_app_views_users_index_html_erb___3592670951755992954_70215580220040'
app/controllers/users_controller.rb:33:in `index'

1 个答案:

答案 0 :(得分:0)

belongs_to :department类中尝试belongs_to :departments而不是User