2012-06-25 90 views
0

比方說,你有以下型號:檢索模型屬性

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"] 
+0

不是'Comment.first.id'工作嗎?編輯 –

回答

0

我真的不明白你想達到什麼。我看到你正在使用多態關聯,你需要訪問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 

請具體談談你的目標。

+0

,希望我更清楚地說明我想使用類似sql的查詢字符串來訪問模型屬性。 – rnd

0

我認爲你正在尋找一種方式從評論訪問用戶。

@comment是第一個評論:

@comment = Comment.first

要訪問的作者,你只需要輸入@comment.user,如果你需要一個用戶的名字,你會做@comment.user.name。這只是OOP

如果您需要評論的ID,你會做@comment.id

0

因爲userid只是方法,你可以那樣稱呼他們:

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

或者,你可以建立你的查詢無論如何你喜歡:

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

但它看起來像你沒有這樣認爲真的Rails方式。我想你有你的理由。