【问题标题】:Find objects through multiple conditions in rails通过rails中的多个条件查找对象
【发布时间】:2015-11-16 22:49:28
【问题描述】:

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

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

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

问题.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

用户.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

【问题讨论】:

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


    【解决方案1】:

    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 等)。

    【讨论】:

    • 效果很好!!我总是很接近得到它,但有些东西会把它扔掉。这正是我正在寻找的实现。再次感谢您的帮助。
    猜你喜欢
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多