0

假设您有以下模型:

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"]
4

3 回答 3

0

因为userandid只是方法,你可以这样称呼它们:

comments.send('user').send('id')

或者,您可以随心所欲地构建查询:

Comment.includes(:users).where("#{User::columns[1]} = ?", @some_name)

但似乎你并没有真正思考 Rails 方式。我想你有你的理由。

于 2012-06-25T14:01:18.143 回答
0

我认为您正在寻找一种从评论中访问用户的方法。

让我们@comment成为第一条评论:

@comment = Comment.first

要访问作者,您只需输入@comment.user和 If you need the name you would do @comment.user.name。这只是OOP

如果您需要该评论的 id,您会这样做@comment.id

于 2012-06-25T13:13:09.033 回答
0

我真的不明白你想要达到什么目的。我看到您正在使用多态关联,您需要在comment.user.name模型中访问吗?has_many :comments, :as => :authorUser

对于你的多态关联,你应该有

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

请更具体地说明您的目标。

于 2012-06-25T13:01:28.217 回答