首先,我向您展示我如何添加belongs_to关联:
的 user.rb:
class User < ActiveRecord::Base
[...]
has_many :schedules
[...]
end
计划模型:( console-command)
rails g model Schedule user_id titel location time
的 schedule.rb:
class Schedule < ActiveRecord::Base
belongs_to :user
end
的 routes.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
的欢迎\ index.html.erb:
[...]
<% if current_user %>
<%= for schedule in @schedules do %>
<strong><%= schedule.titel %></strong>
<%= schedule.time %>
<%= schedule.location %>
<% end %>
<% else %>
[...]
db:migrate工作正常。
的结果:
例外: 未定义的方法`时间表&#39;为零:NilClass
def index
@schedules = current_user.schedules
end
<小时/> 好吧,没有时间表方法。但我这样做是因为 Rich Peck 说,我认为他知道该怎么做 为了更好地理解,我应该添加第一个question 简短信息:
<小时/> 修改
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
答案 0 :(得分:0)
Frederick Cheung 表示协会没有任何问题
问题是 current_user是nil ,因此我将其修复如下:
<强> welcome_controller.rb:强>
class WelcomeController < ApplicationController
def index
if(current_user)
@schedules = current_user.schedules
end
end
end