假设您有以下模型:
class User < ActiveRecord::Base
has_many :comments, :as => :author
end
class Comment < ActiveRecord::Base
belongs_to :user
end
假设 User 有一个属性名称,Ruby/Rails 中是否有任何方法可以使用表名和列访问它,类似于您在 select 或 where 查询中输入的内容?就像是:
Comment.includes(:author).first.send("users.name")
# or
Comment.first.send("comments.id")
编辑:我想要实现的是使用string访问模型对象的属性。对于简单的情况,我可以只使用object.send attribute_name但这在访问“嵌套”属性(例如Comment.author.name)时不起作用。
基本上,我想使用 ActiveRecord 在 where() 和 select() 方法中使用的类似 sql 的语法来检索模型属性,例如:
c = Comment.first
c.select("users.name") # should return the same as c.author.name
编辑2:更准确地说,我想解决以下问题:
obj = ANY_MODEL_OBJECT_HERE
# Extract the given columns from the object
columns = ["comments.id", "users.name"]