【问题标题】:Ruby on rails - access model data within another model [closed]Ruby on rails - 在另一个模型中访问模型数据 [关闭]
【发布时间】:2014-08-05 08:22:06
【问题描述】:

我想访问从 OtherModel.rb 到 MyModel.rb 的列。这可能吗?

如果我要访问的数据位于它自己的模型中,这就是它的样子。这很好用

//MyModel.rb

def to_param
  self.name
end

但我不知道如何从其他模型访问数据。 这是我想要的一个例子:

//MyModel.rb

def to_param
  OtherModel.name
end

【问题讨论】:

  • 可以访问其他模型的实例,但这确实不是一个好习惯。
  • 我可以知道怎么做吗?我现在很绝望
  • 其他模型的哪个实例?
  • 嗨@FrederickCheung,你是什么意思?对不起,我是 Rails 的新手
  • 好吧,OtherModel 的表中大概有很多行。在所有这些中,你想要哪个名字属性?

标签: ruby-on-rails rails-models


【解决方案1】:

模型感知!!


对象

描述您遇到的问题的最佳方式是概述 Ruby(以及基于 Ruby 语言构建的 Rails)是object-orientated

与流行的看法相反,面向对象不仅仅是一个流行词——它意味着你的应用程序的每个元素都应该围绕对象构建。对象本质上是“变量”,其中包含一组属性和附加到它们的其他数据:

在 Rails 中,对象被创建为模型(类)的实例


修复

当您调用OtherModel.name 时,您并未初始化相关类的实例,因此意味着您将无法显示它所具有的任何属性

为确保可以解决此问题,您需要确保加载OtherModel 对象的实例,以确保您能够调用相关数据:

#app/models/my_model.rb
Class MyModel < ActiveRecord::Base
   def to_param
      return OtherModel.first.name #-> returns first instance of `OtherModel` & then displays "name"
   end
end

协会

更好的选择是利用ActiveRecord Associations

#app/models/my_model.rb
Class MyModel < ActiveRecord::Base
   has_many :other_models
end

#app/models/other_model.rb
Class OtherModel < ActiveRecord::Base
   belongs_to :my_model
end

这意味着您可以调用以下命令:

@my_model = MyModel.find 1
@my_model.other_models.each do |other|
   puts other.name
end

查看 ActiveRecord 关联如何创建关联模型的实例?这允许您从“父”模型的实例中调用它,而无需重新初始化它

--

委托

您也可以使用delegate 方法,具体取决于您的关联设置:

#app/models/my_model.rb
Class MyModel < ActiveRecord::Base
    belongs_to :other_model
    delegate :name, to: :other_model, prefix: true
end

#app/models/other_model.rb
Class OtherModel < ActiveRecord::Base
    has_many :my_models
end

这将允许您调用:

@my_model = MyModel.find 1
@my_model.other_model_name

必须注意delegate 方法适用于belongs_to 关系

【讨论】:

  • 嗨.. 是否可以添加过滤器?例如返回 OtherModel.where("other_model_id = ?" my_model_id).first.name 提前感谢 :)
  • 您所指的“过滤器”可以通过 ActiveRecord 关联轻松实现,正如我在回答中提到的那样
【解决方案2】:

OtherModel.new 将创建 OtherModel 的新实例。

或者您可以使用 OtherModel.all.first 作为 OtherModel 的第一条记录。根据上下文,我们可以通过任何实例访问 name 列

提供的名称是 OtherModel 的列的名称

MyModel.rb

def to_param
  OtherModel.new.name
  OtherModel.all.first.name
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多