通过rails

时间:2015-11-16 03:51:55

标签: ruby-on-rails ruby-on-rails-4

对于测验应用程序,我正在尝试显示当前用户尚未回答的ACTIVE问题。答案表有一个我正在尝试使用的user_id和question_id。我以为我接近以下查询(在static_pages_controller.rb中:

@questions = Question.active_question.where.not(id: @user.answers)

当我测试它时似乎并不适用于所有情况。我觉得我很亲密,但不知道从哪里开始。 Rails的新手非常感谢任何帮助!

question.rb

 has_many :answers

  scope :active_questions, -> { where("? BETWEEN start AND end", Time.now.to_date)}
  scope :activeAtDate, lambda{ |date = Date.today| where("? BETWEEN start AND end", date) }

answer.rb

  belongs_to :question
  belongs_to :user

  scope :user_answered, lambda {|q| where("question_id == (?)", q) }

  validates_uniqueness_of :question_id, scope: :user_id

user.rb

 has_many :answers

static_pages_controller.rb

 def index
    @user = current_user

    if user_signed_in?  
      if @user.manager_id != nil
        @manager = @user.manager_id
      end
      @my_team = User.where("manager_id = ? AND id != ?", @manager, @user.id)
      @questions = Question.active_question.where.not(id: @user.answers)

    end

    @new_answer = Answer.new


  end

1 个答案:

答案 0 :(得分:0)

  

Rails的新手

欢迎 - 到目前为止你做得很好。

我原本以为你应该从你的@user.answers协会调用问题 - 然后我意识到你想要用户没有回答的问题。

...所以我会做以下事情:

#app/models/user.rb
class User < ActiveRecord::Base
   def non_participating_questions
     answered_questions = self.answers.pluck(:question_id)
     Question.active_questions.where.not(id: answered_questions)
   end
end

这将允许您致电:

@user = User.find params[:id]
@questions = @user.non_participating_questions

将此附加到User模型的好处是您可以使用instance_method(因此您不必每次都传递@user)。这也意味着您能够处理user所拥有的所有关联数据(answers等)。