Reputation: 4428
I have a Comment
model which has-many attachments
. What I want to return, is all of the comments which either have one or more attachment records, OR whose comment is longer than 250 characters.
Is there any way I can do this without writing it entirely in pure SQL? I'm struggling to build up a WHERE clause in just the rails method. It's not quite as simple as I'd hoped :(
Ideally I want this to be a scope but whatever will work is fine
Upvotes: 0
Views: 86
Reputation: 1399
Jump into the irb or rails c (console) do this from command-line to get it then plug it in.
c = YourCommentModel.where('attachments > ?', 1)
len250 = c = YourCommentModel.where('attachments.length> ?', 250)
first one gives comments of greater than 1, second gives comments > 250
Upvotes: 0
Reputation: 3237
You could try:
Comment.includes(:attachments).where('attachments.comment_id IS NOT NULL OR LEN(comments.content) > 250')
Upvotes: 3
Reputation: 6826
The WHERE clause should follow the pattern o the following pseudo-code
WHERE Length(Comment_field) > 250
OR EXISTS (Select COMMENT_ID from attachments)
Upvotes: 0