![](/img/trans.png)
[英]Why do I get 'undefined method `>=' for nil:NilClass' in do loop?
[英]Why isn't this portion of HTML rendering and why do I get a undefined method `cardsets' for nil:NilClass in Rails?
我正在嘗試在Rails中添加一個flashcards(cardsets)功能,我在實現這個時遇到了一些問題,因為我得到一個undefined method
cardsets'為nil:NilClass`錯誤
如果我改變,我可以讓頁面呈現: <% if @user.cardsets.any? %>
<% if @user.cardsets.any? %>
到<% unless @cardsets.any? %>
<% unless @cardsets.any? %>
但是當我這樣做時會顯示相應的卡片組。 以下是產生此錯誤的html.erb代碼:
<% provide(:title, "Flashcards") %>
<h1>Flashcards</h1>
<div class="row">
<aside class="span3">
<%= render "shared/cardset_form" %>
</aside>
<div class="span6">
**<% if @user.cardsets.any? %>**
<h3>Flashcard Sets (<%= @user.cardsets.count %>)</h3>
<ol class="cardsets">
<% @user.cardsets.each do |cardset| %>
<li>
<span class="topic"><%= link_to cardset.topic, show_cardset_path(cardset) %></span>
<%= link_to "edit", edit_cardset_path(cardset) %>
<%= render partial: "shared/delete_link", locals: {item: cardset} %>
</li>
<% end %>
</ol>
<% end %>
</div>
</div>
我已經為nil:NilClass`錯誤生成了undefined method
cardsets的行。
這就是我的cardsets_controller.rb中的內容:
class CardsetsController < ApplicationController
before_action :signed_in_user, only: [:new, :index, :create, :edit, :destroy, :update]
before_action :correct_user, only: [:edit, :update, :destroy]
def index
@cardsets = Cardset.all
end
def show
@cardset = Cardset.find(params[:id])
end
def create
@cardset = current_user.cardsets.build(cardset_params)
if @cardset.save
flash[:success] = "A new set of flashcards have been created!"
redirect_to @cardset
else
render "new"
end
end
def new
@cardset = Cardset.new
end
def edit
end
def update
@cardset = Cardset.find(params[:id])
if @cardset.update_attributes(cardset_params)
flash[:success] = "You've updated your flashcards!"
redirect_to @cardset
else
render "edit"
end
end
def destroy
@cardset = Cardset.find(params[:id])
@cardset.delete
redirect_to cardsets_path
end
private
def cardset_params
params.require(:cardset).permit(:topic, :description)
end
def correct_user
@cardset = current_user.cardsets.find_by_id(params[:id])
redirect_to root_url if @cardset.nil?
end
end
這是我的cardset.rb文件中的代碼:
class Cardset < ActiveRecord::Base
belongs_to :user
validates :user_id, presence: true
validates :topic, presence: true
end
這是我的user.rb文件中的代碼:
class User < ActiveRecord::Base
has_many :cardsets
(...a bunch of other code...)
end
如果有人能就我可能出錯的地方提供一些幫助或建議,我將非常感激!
謝謝!
據我所知,你沒有在你的Controller中設置@user
,所以@user
是nil
。
您可能想要定義@user
或者您打算使用@cardsets
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.