Salil
Salil

Reputation: 47482

How to add conditional has_many associations

I have following DB structure

tasks

id   name   parent_id
1    Abc    nil
2    Pqr    1

comments

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

My requirement is to have an associations such that for the parent as well as children i should get the parent comments i.e. for both the above tasks i should get ['This is sample comment', 'This is another sample comment'] as child tasks will not have any comments.

I tried something like following but it doesn't work

task.rb

has_many :comments,  -> (o) { where(comments: {task_id: [o.id, o.parent_id]}) }

Upvotes: 0

Views: 1279

Answers (1)

chumakoff
chumakoff

Reputation: 7034

It does not work because your new condition is combined with the default one that comes from has_many. You can use unscope method to cancel the default condition:

has_many :comments, -> (task) { unscope(:where).where(comments: {task_id: [task.id, task.parent_id]}) }

NOTE: This will break default_scope of the Comment model if there is one.

In Rails5 you would be able to add OR condition to the default one:

has_many :comments, -> (task) { or(comments: {task_id: task.parent_id}) }

Upvotes: 1

Related Questions