[英]belongs_to - undefined method
首先,我向您展示如何添加belongs_to關聯:
user.rb:
class User < ActiveRecord::Base
[...]
has_many :schedules
[...]
end
調度模型:(控制台命令)
rails g model Schedule user_id titel location time
schedule.rb:
class Schedule < ActiveRecord::Base
belongs_to :user
end
route.rb:
Calendar::Application.routes.draw do
[...]
resources :users, only: :index
[...]
end
welcome_controller.rb:
class WelcomeController < ApplicationController
def index
@schedules = current_user.schedules
end
end
welcome \\ index.html.erb:
[...]
<% if current_user %>
<%= for schedule in @schedules do %>
<strong><%= schedule.titel %></strong>
<%= schedule.time %>
<%= schedule.location %>
<% end %>
<% else %>
[...]
db:migrate工作正常。
結果:
異常: nil:NilClass的未定義方法“ schedules”
def index
@schedules = current_user.schedules
end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception helper_method :current_user def current_user # Note: we want to use "find_by_id" because it's OK to return a nil. # If we were to use User.find, it would throw an exception if the user can't be found. @current_user ||= User.find_by_id(session[:user_id]) if session[:user_id] @current_user ||= User.find_by_authentication_token(cookies[:auth_token]) if cookies[:auth_token] && @current_user.nil? @current_user end end
正如張建宗所說,該協會沒有任何問題。
問題在於current_user為nil ,所以我像這樣修復它:
welcome_controller.rb:
class WelcomeController < ApplicationController
def index
if(current_user)
@schedules = current_user.schedules
end
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.