Ruby on rails Rails错误未定义方法'id';零级:零级
我试图将数据从术语模型中获取到视图中,但出现了一个错误 术语模型:Ruby on rails Rails错误未定义方法'id';零级:零级,ruby-on-rails,ruby,model-view-controller,Ruby On Rails,Ruby,Model View Controller,我试图将数据从术语模型中获取到视图中,但出现了一个错误 术语模型: Phrases_term(id, term_id, phrase_id) 短语\u术语\u controller.rb class PhrasesTermsController < ApplicationController before_action :authenticate_user! before_action :set_term def new @phrases_term = Phrase
Phrases_term(id, term_id, phrase_id)
短语\u术语\u 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
class PhrasesTermsController
短语\u术语显示视图,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>
身份证件
短语\u ID
术语识别码
|
我得到的错误是:
错误:为nil:NilClass定义了方法“id”
由于您的
show.html.erb
视图不知道@phrases\u term
是什么,因此您得到了nil:NilClass的未定义的方法“id”错误。因此,对尚不存在的变量调用id
方法会引发错误。您需要在正确的操作下定义在正确的控制器中使用的变量。因此,加入:
def show
@phrases_term = PhrasesTerm.find(params[:id])
end
在您的phrases\u terms\u controller.rb中,应该可以解决此错误。您得到了一个未定义的nil:NilClass方法“id”错误,因为您的show.html.erb
视图不知道@phrases\u term
是什么。因此,对尚不存在的变量调用id
方法会引发错误。您需要在正确的操作下定义在正确的控制器中使用的变量。因此,加入:
def show
@phrases_term = PhrasesTerm.find(params[:id])
end
在你的短语中\u terms\u controller.rb应该可以解决这个错误