2011-09-22 46 views
4

我試圖顯示用戶發佈的紋身最近添加的評論。所以,如果我發佈紋身,然後user_b張貼「嘿,我喜歡你的紋身」,然後我試圖得到只是評論。如何使我的自定義mySQL查詢在rails 3中?

的所有IM首先使用acts_as_commentable_with_threading寶石其犯規創建表即時試圖加入一個外鍵。所以我的控制器無法找到tattoo_id,它必須尋找commentable_id

在控制器中,我將不得不調用評論模型,然後傳遞一些SQL的東西,但顯然我不知道如何傳遞自定義SQL查詢紅寶石,因爲即使我的查詢字符串在終端中工作,當我嘗試在rails中使用它時,我會收到各種廢話。

進出口基本試圖做到這一點:

SELECT comments.id FROM comments,tattoos WHERE commentable_id = tattoos.id AND 
tattoos.member_id = #{current_user} 

,其中#{} CURRENT_USER將是CURRENT_USER傳入

+3

不要使用'#{CURRENT_USER}'。請參見[SQL注入](http://guides.rubyonrails.org/security.html#sql-injection)。 – Zabba

回答

4

我覺得本的方法是最好的,但以供將來參考,如果你遇到更復雜的東西,你可以隨時使用SQL例如:

Comment.find_by_sql("SELECT comments.* FROM comments,tattoos WHERE commentable_id = tattoos.id AND tattoos.member_id = ?", current_user) 
+0

ahhh這真是太棒了謝謝! – rugbert

7

你沒有經歷這麼多跳火圈做到這一點。 acts_as_commentable分配一個多態關聯,所以你應該將它設置這樣的:

class Comment < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :commentable, :polymorphic => true 
end 

class Tattoo < ActiveRecord::Base 
    has_many :comments, :as => :commentable 
end 

class User 
    has_many comments 
end 

然後,您可以訪問聯想像往常一樣:

Tattoo.where(:member_id => current_user).first.comments 

http://railscasts.com/episodes/154-polymorphic-association對於一般的教程協會如何多態性的工作。恰恰相反,這個railscast使用了多種形式的commentable,所以你應該可以直接跟隨,如果你願意的話。

+0

好吧,acts_as_commentable使評論模型屬於評論者(用戶離開評論),所以不會工作。但是,無論如何,這確實爲我闡明瞭Rails和SQL。謝謝! – rugbert

+0

好吧,acts_as_commentable_on的工作方式是評論模型屬於您分配給它的任何內容,在這種情況下是用戶。但你指定一個單獨的模型(或者如果你想要的話)是可以評論的,在我的例子中是一個紋身,要評論。 Acts_as_commentable然後分配「commentable_id」列來引用被評論的紋身。對不起,我需要花時間來證明我在將來閱讀我的問題和帖子 – rugbert

相關問題