簡體   English   中英

owners_to-未定義的方法

[英]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


好吧,沒有時間表方法。 但是我做到了,就像里奇·佩克Rich Peck)所說的那樣,我認為他知道該怎么做。
為了更好地理解,我應該添加第一個問題
簡短信息:
有一個html表,該表應具有以下內容:標頭日期,標題,時間,位置。
如您所見,這是一個時間表。
調度模型屬於用戶模型。
我想在welcome-index-view中使用schedule-model。
希望您掌握所有信息,對我有幫助。
誰能幫我修復它?


編輯:

application_controller.rb:

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM