2017-08-31 79 views
1

我已經在我的ApplicationController定義一個實例變量這樣的:現在如何從Rails模型訪問實例變量?

@team = Team.find(params[:team_id]) 

,在我EventsCreator模式,我想從上面的訪問@team

class EventsCreator 
    # ... 

    def team_name 
    name = @team.name 
    # ... 
    end 

    # ... 
end 

與該代碼我得到出現以下錯誤:

undefined method `name' for nil:NilClass

我該如何從模型中訪問像這樣的實例變量?有沒有更好的方法或更好的做法來做到這一點?


編輯1:

event.rb模型是包含這也是保存在數據庫中的公共信息模型:

class Event < ApplicationRecord 
    belongs_to :team 
    attr_accessor :comment 
    ... 
end 

events_creator.rb模式是怎麼樣的延伸到event.rb。它包含一些邏輯,例如重複事件:

class EventsCreator 
    include ActiveModel::Model 
    attr_accessor :beginning, :ending, :repeat_frequency, :repeat_until_date 
    ... 
end 

EventsCreator不直接在數據庫中創建記錄。它只是執行一些邏輯並通過Event模型保存數據。

現在不具有直接關係到team.rb我希望能夠訪問變量@team的實例,它是在application_controller.rb定義:

class ApplicationController < ApplicationController::Base 
    before_action :set_team_for_nested 

    private 
    def set_team_for_nested 
    @team = Team.find(params[:team_id]) 
    end 
end 

routes.rb文件中嵌套team所有路線,因爲我需要的team_id對於每一個動作:

Rails.application.routes.draw do 
    resources :teams do 
    resources :events 
    get '/events_creator', to: 'events_creator#new', as: 'new_events_creator' 
    post '/events_creator', to: 'events_creator#create', as: 'create_events_creator' 
    end 
end 

現在我不知道如何訪問@team實例變量(我思想是爲整個應用程序定義的)。由於我對Rails很陌生,因此可能會搞砸了一些事情,請告訴我是否有更好的方法來實現這一點。

+0

可以,例如,通過它在EventCreator的初始化。 'event_creator = EventCreator.new(@team)' –

+0

我刪除了我的答案,因爲它不適合你的問題。我現在建議像@patkoperwas一樣。 – Chris

回答

1

您必須將team作爲參數傳遞到您的類。

class EventsCreator 
    attr_reader :team 
    def initialize(team) 
    @team = team 
    end 

    def some_method 
    puts team.name 
    end 
end 

# Then in your controller you can do this 
def create 
    EventsCreator.new(@team) 
end 

如果您計劃在包括ActiveModel::Model那麼你可以做

class EventsCreator 
    include ActiveModel::Model 
    attr_accessor :team 

    def some_method 
    puts team.name 
    end 
end 

# And then in your controller it's the same thing 
def create 
    EventsCreator.new(@team) 
end 
-1

簡單

class EventCreator 

    ... 

    def team_name 
    name #will return name of class instance 
    #or do something with it 
    end 
end 
+1

我不知道這是一個答案,因爲你的*解釋*是「簡單的」我認爲你已經做了什麼,但 – engineersmnky

+0

(s)他想訪問一個實例屬性,我試圖展示如何做。怎麼了? - )) – marmeladze

+0

您只是展示瞭如何調用另一個(未定義的)方法和/或聲明一個不存在的局部變量。你沒有解釋,也沒有實例變量。這個地址的地址實際上是 – engineersmnky