【问题标题】:How to access instance variable from a Rails model?如何从 Rails 模型访问实例变量?
【发布时间】:2017-09-04 16:24:40
【问题描述】:

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

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

现在,在我的EventsCreator 模型中,我想从上面访问@team

class EventsCreator
  # ...

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

  # ...
end

使用该代码,我收到以下错误:

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 很陌生,我可能会搞砸一些事情,请告诉我是否有更好的方法来实现同样的目标。

【问题讨论】:

  • 例如,您可以在 EventCreator 的初始化程序中传递它。 event_creator = EventCreator.new(@team)
  • 我删除了我的答案,因为它不适合您的问题。我现在建议和@patkoperwas 一样。

标签: ruby-on-rails ruby activemodel


【解决方案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

【讨论】:

    【解决方案2】:

    简单

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

    【讨论】:

    • 我不确定这是怎么回答的,因为你的 解释 是“简单的”,我认为你已经做到了,但
    • (s)他想访问一个实例属性,我试图展示如何去做。怎么了? -))
    • 您只是展示了如何调用另一个(未定义的)方法和/或声明一个不存在的局部变量。你没有解释,当然也没有实例变量。这以解决实际问题的方式
    • 您的评论是基于不合时宜的。我已经发布了类似的问题 - stackoverflow.com/revisions/… 刚刚意识到它已被编辑并演变成一个完全不同的问题。
    猜你喜欢
    • 2011-05-06
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-15
    相关资源
    最近更新 更多