rug*_*ert 4 activerecord ruby-on-rails ruby-on-rails-3
我试图显示用户发布的纹身最近添加的评论.所以,如果我贴了一个纹身,然后user_b发布了"嘿,我喜欢你的纹身",那么我试图得到评论.
首先,我使用acts_as_commentable_with_threading gem,它不会为我试图加入的表创建外键.所以我的控制器无法寻找tattoo_id,它必须寻找commentable_id
在控制器中,我必须调用Comment模型,然后将一些SQL内容传递给它,但显然我不知道如何将自定义SQL查询传递给ruby,因为即使我的查询字符串在终端中工作,我也会得到各种各样的废话.试图在铁轨中使用它.
我基本上试图这样做:
SELECT comments.id FROM comments,tattoos WHERE commentable_id = tattoos.id AND
tattoos.member_id = #{current_user}
Run Code Online (Sandbox Code Playgroud)
其中#{current_user}将是传入的current_user.
你没有必要通过这么多的箍来完成这个任务.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
Run Code Online (Sandbox Code Playgroud)
然后您可以照常访问该关联:
Tattoo.where(:member_id => current_user).first.comments
Run Code Online (Sandbox Code Playgroud)
有关多态关联如何工作的一般教程,请参见http://railscasts.com/episodes/154-polymorphic-association.事实上,这个railscast完全使用:可评论作为多态的例子,所以如果你愿意,你应该能够直接跟随.
| 归档时间: |
|
| 查看次数: |
2150 次 |
| 最近记录: |