简体   繁体   中英

Rails error-undefined method `id' for nil:NilClass

I'm trying to get the data from the phrases_term model to the view, but I'm getting an error.

Phrases_term model:

Phrases_term(id, term_id, phrase_id)

phrases_terms_controller.rb

class PhrasesTermsController < ApplicationController
  before_action :authenticate_user!
  before_action :set_term

  def new
    @phrases_term = PhrasesTerm.new
  end

  def create
    @phrases_term = @term.phrases_terms.new(phrases_term_params)
    if @phrases_term.save
      redirect_to term_phrases_term_path(@term, @phrases_term), notice: "Phrases_Term was successfully created"
    else
      render "new"
    end
  end

  private

  def phrases_term_params
    params.require(:phrases_term).permit(:term_id, :phrase_id)
  end

  def set_term
    @term = Term.find(params[:term_id])
  end
end

Phrases_term show view, show.html.erb:

<div class="container">
<table class="table">
    <thead>
      <tr>
        <th>ID</th>
        <th>Phrases_ID</th>
        <th>Term_ID</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><%= @phrases_term.id %></td>
        <td><%= @phrases_term.term_id %></td>
        <td><%= @phrases_term.phrase_id %></td>
  </table>
<%= link_to 'Back', terms_path %> |
<%= link_to 'Edit', edit_term_path %> 
</div>

The error I'm getting:

Error: Eundefined method `id' for nil:NilClass

You're getting an undefined method 'id' for nil:NilClass error because your show.html.erb view doesn't know what @phrases_term is. Hence calling the id method on a variable that doesn't exist yet throws an error. You need to define the variable you're using in the right controller under the right action. So adding:

def show
  @phrases_term = PhrasesTerm.find(params[:id])
end

in you phrases_terms_controller.rb should solve the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM