Ruby on rails RubyonRails-访问另一个模型中的模型数据

Ruby on rails RubyonRails-访问另一个模型中的模型数据,ruby-on-rails,rails-models,Ruby On Rails,Rails Models,我想访问从OtherModel.rb到MyModel.rb的列。可能吗 如果我想要访问的数据位于模型中,它就是这个样子。这个很好用 //MyModel.rb def to_param self.name end 但我不知道如何访问其他模型的数据。 以下是我想要的示例: //MyModel.rb def to_param OtherModel.name end OtherModel.new将创建OtherModel的新实例 或者您可以使用OtherModel.all.first作为

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

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

//MyModel.rb

def to_param
  self.name
end
但我不知道如何访问其他模型的数据。 以下是我想要的示例:

//MyModel.rb

def to_param
  OtherModel.name
end

OtherModel.new将创建OtherModel的新实例

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

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

MyModel.rb

def to_param
  OtherModel.new.name
  OtherModel.all.first.name
end
模特儿


对象

描述这个问题的最好方法是概述Ruby(由于构建在Ruby语言之上,因此&Rails)是

与流行的观点相反,面向对象不仅仅是一个流行词,它意味着应用程序的每个元素都应该围绕对象构建。对象本质上是“变量”,具有附加到它们的属性和其他数据的集合:

在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
这意味着您可以调用以下命令:

@my_model = MyModel.find 1
@my_model.other_models.each do |other|
   puts other.name
end
查看ActiveRecord关联如何创建关联模型的实例?这允许您从“父”模型的实例调用它,而无需重新初始化它

--

代表

根据您的关联设置,您也可以使用该方法:

#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

必须注意的是,
delegate
方法仅适用于
属于
关系

它可以访问其他模型的实例,但实际上不是很好的做法。我可以知道怎么做吗?我现在非常绝望,其他模型的哪一个实例?嗨,FrederickCheung,你是什么意思?很抱歉,我是railsWell的新手,估计OtherModel的表中有很多行。在所有这些中,你想要哪一个的名字属性?嗨。。是否可以添加过滤器?例如,返回OtherModel.where(“other\u model\u id=?”my\u model\u id)。first.name提前感谢:)您所指的“过滤器”可以通过ActiveRecord关联轻松实现,正如我在回答中提到的
#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