在我的申请中,我有问题和答案:
resources :questions do
resources :answers
end
每个问题都有一个名为answers_count
的列,用于存储答案数量。
我的问题是我没有答案就无法得到大量的问题。在我的评论控制器中,我有这个(问题属于评论):
def show
@comment = Comment.find params[:id]
@unanswered = @comment.questions.select('comments.*, count(questions.id) as answer_count')
.joins(:answers)
.group('questions.id')
.having('answer_count == 0')
end
然后在我的评论节目视图中我有这个:
<% unless @unanswered.blank? %>
action
<% end %>
但是我收到了这个错误:
Association named 'answers' was not found on Question; perhaps you misspelled it?
以下是问答模型:
class Question < ActiveRecord::Base
has_one :answer
end
class Answer < ActiveRecord::Base
belongs_to :question
end
答案 0 :(得分:0)
在has_many :answers
中设置has_one
而不是Question
并设置counter_cache选项:
class Answer < ActiveRecord::Base
belongs_to :question, counter_cache: true
end
然后
@question.where('answer_count == 0')
如果问题只有一个答案,那么你不需要存储answer_count,也不需要counter_cache。应该是这样的:
Question.joins('LEFT OUTER JOIN answers ON answers.question_id = questions.id')
.where('answers.questions_id IS NULL')