检索模型属性
比方说,你有以下型号:检索模型属性
class User < ActiveRecord::Base
has_many :comments, :as => :author
end
class Comment < ActiveRecord::Base
belongs_to :user
end
假设用户有一个属性的名字,有没有用Ruby/Rails的任何方式使用表名来访问它,列,类似于你在select或where查询中输入的内容? 喜欢的东西:
Comment.includes(:author).first.send("users.name")
# or
Comment.first.send("comments.id")
编辑:我试图实现使用串正在访问模型对象的属性。对于简单情况,我可以使用object.send attribute_name,但在访问“嵌套”属性时不起作用,如Comment.author.name。
基本上我想检索使用在其中(使用的ActiveRecord的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"]
我真的不明白你想达到什么。我看到你正在使用多态关联,你需要访问comment.user.name
,而你的User
模型中有has_many :comments, :as => :author
?
对你的多态关联,你应该有
class Comment < ActiveRecord::Base
belongs_to :author, :polymorphic => true
end
如果你想访问comment.user.name
,你也可以有
class Comment < ActiveRecord::Base
belongs_to :author, :polymorphic => true
belongs_to :user
end
class User < ActiveRecord::Base
has_many :comments, :as => :author
has_many :comments
end
请具体谈谈你的目标。
,希望我更清楚地说明我想使用类似sql的查询字符串来访问模型属性。 – rnd
我认为你正在寻找一种方式从评论访问用户。
让@comment
是第一个评论:
@comment = Comment.first
要访问的作者,你只需要输入@comment.user
,如果你需要一个用户的名字,你会做@comment.user.name
。这只是OOP。
如果您需要评论的ID,你会做@comment.id
因为user
和id
只是方法,你可以那样称呼他们:
comments.send('user').send('id')
或者,你可以建立你的查询无论如何你喜欢:
Comment.includes(:users).where("#{User::columns[1]} = ?", @some_name)
但它看起来像你没有这样认为真的Rails方式。我想你有你的理由。
不是'Comment.first.id'工作吗?编辑 –