如何从 Rails 模型访问实例变量?

How to access instance variable from a Rails model?

我在 ApplicationController 中定义了一个实例变量,如下所示:

@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 没有直接关系,我希望能够访问 application_controller.rb:

中定义的实例变量 @team
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 的新手,我可能把事情搞砸了,请告诉我是否有更好的方法来实现同样的目标。

简单

class EventCreator

  ...

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

您必须将 team 作为参数传递给您的 class。

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