【发布时间】:2016-12-28 10:51:20
【问题描述】:
我有以下数据库结构
任务
id name parent_id
1 Abc nil
2 Pqr 1
cmets
id task_id body
1 1 This is sample comment
2 1 This is another sample comment
task.rb
has_many :comments
comment.rb
belongs_to :task
我的要求是有一个关联,这样对于父母和孩子我都应该得到父 cmets,即对于上述两个任务我应该得到 ['This is sample comment', 'This is another sample comment']因为子任务不会有任何 cmets。
我尝试了类似以下的方法,但它不起作用
task.rb
has_many :comments, -> (o) { where(comments: {task_id: [o.id, o.parent_id]}) }
【问题讨论】:
-
但是不行 -- 有没有错误?
标签: ruby-on-rails ruby-on-rails-4 associations conditional-associations