【问题标题】:Rails undefined method `email' for nil:NilClass用于 nil:NilClass 的 Rails 未定义方法“电子邮件”
【发布时间】:2019-02-27 20:35:36
【问题描述】:

我在 Rails 应用程序中收到以下错误。你能帮帮我吗?

连接两个表时出现错误。 用户想要使用表格。我正在尝试从一个表中管理经理 ID 和用户 ID 字段。

ruby 2.5.1p57(2018-03-29 修订版 63029)[x86_64-darwin17]

Rails 5.2.2

Database Design

Error Message

数据库设计和表格 schema.rb:

ActiveRecord::Schema.define(version: 2019_02_24_160401) do

  create_table "projects", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
    t.string "name"
    t.text "description"
    t.string "company"
    t.bigint "manager_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["manager_id"], name: "index_projects_on_manager_id"
  end

  create_table "users", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "username", default: "", null: false
    t.string "fullname", default: ""
    t.bigint "manager"
    t.string "company", default: ""
    t.string "department", default: ""
    t.boolean "isadmin", default: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end

  add_foreign_key "projects", "users", column: "manager_id"
end

projects_controller.rb

class ProjectsController < ApplicationController
  before_action :set_project, only: [:show, :edit, :update, :destroy]
  before_action :find_users, only: [:index, :show, :new, :edit]
  # GET /projects
  # GET /projects.json
  def index
    @projects = Project.all
  end

  # GET /projects/1
  # GET /projects/1.json
  def show
  end

  # GET /projects/new
  def new
    @project = Project.new
  end

  # GET /projects/1/edit
  def edit
  end

  # POST /projects
  # POST /projects.json
  def create
    @project = Project.new(project_params)

    respond_to do |format|
      if @project.save
        format.html { redirect_to @project, notice: 'Project was successfully created.' }
        format.json { render :show, status: :created, location: @project }
      else
        format.html { render :new }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /projects/1
  # PATCH/PUT /projects/1.json
  def update
    respond_to do |format|
      if @project.update(project_params)
        format.html { redirect_to @project, notice: 'Project was successfully updated.' }
        format.json { render :show, status: :ok, location: @project }
      else
        format.html { render :edit }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /projects/1
  # DELETE /projects/1.json
  def destroy
    @project.destroy
    respond_to do |format|
      format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_project
      @project = Project.find(params[:id])

    end

    def find_users
      @users = User.all.order('created_at desc')
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def project_params
      params.require(:project).permit(:name, :description, :user_id)
    end
end

模型文件夹中的模型文件 project.rb 和 user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  has_many :projects
end

class Project < ApplicationRecord
  belongs_to :user
end

调用我的代码电子邮件列 index.html.erb

<p id="notice"><%= notice %></p>

<h1>Projects</h1>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Description</th>
      <th>Company</th>
      <th>Manager</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @projects.each do |project| %>
      <tr>
        <td><%= project.name %></td>
        <td><%= project.description %></td>
        <td><%= project.company %></td>
        <td><%= project.user.email %></td>
        <td><%= link_to 'Show', project %></td>
        <td><%= link_to 'Edit', edit_project_path(project) %></td>
        <td><%= link_to 'Destroy', project, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to 'New Project', new_project_path %>

【问题讨论】:

  • 你的Projects控制器看起来怎么样?
  • resimag.com/p1/c7e6e3b5f41.png resimag.com/p1/c541f8849df.png
  • 你们有旅游协会吗?
  • 看起来有些Project 没有User。为了防止这种情况,我建议在Project 模型中使用validates :user_id, presence: true
  • 您的projects 表中没有user_id 列,而是manager_id。但同时,没有managers 表,只有users 表。您显然不遵循 Rails 命名约定,因此必须在关联配置中添加更多选项(因为 manager_id 指向 users 表上的外键)。但是,即使您必须做出决定,是否应该将此关联命名为manager(如模型和数据库中)或user(您的视图中的链接)。请澄清!

标签: mysql ruby-on-rails ruby activerecord


【解决方案1】:

您的Project 有一个manager_id,但没有名为managers 的表,而是users。所以在你的项目和用户的关系中,需要使用正确的key。

class User < ApplicationRecord
  has_many :projects, foreign_key: :manager_id
end

class Project < ApplicationRecord
  belongs_to :user, foreign_key: :manager_id
end

【讨论】:

  • 我的问题解决了,谢谢。不知道应该怎么用。
【解决方案2】:

模式中的数据似乎没有很好地起草。 UserManager 是一样的吗?如果不是,您应该在Projects 表中有一个user_id 引用,否则,您必须添加将manager_id 绑定到Users 的适当关联,然后您可以拥有project.manager.email

【讨论】:

  • 用户想要一个表,经理没有表用户表id列=项目表manager_id列
【解决方案3】:

如果用户是 Project 的可选用户,只需调用 project.user&amp;.email

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多