MySQL, Highcharts: “operand should contain 1 colum

2019-09-06 11:24发布

问题:

I am trying to render data on to a spline chart by collecting an array of id's:

Controller

def student_feedback
        difficulty_ids = current_user.school_user.homework_students.pluck(:difficulty)
        @homeworks = HomeworkStudent.where("homework_id = (?)", difficulty_ids).first
    end

The table I am targeting is called homework_students:

create_table "homework_students", force: :cascade do |t|
    t.integer  "school_user_id", limit: 4, null: false
    t.integer  "homework_id",    limit: 4, null: false
    t.datetime "completed_on"
    t.datetime "created_at",               null: false
    t.datetime "updated_at",               null: false
    t.boolean  "completed",      limit: 1
    t.integer  "difficulty",     limit: 4
    t.integer  "interest",       limit: 4
  end

Each student has many different homeworks and they can assign a difficulty value in the difficulty column for each. I am looking to graph this data for each student.

So in the above controller action I am plucking difficulty figures (1 - 5) for each piece of homework the current user is associated with in an array.

In my chart:

...
       }
        },
        series: [{
            name: 'Difficulty',
            data: [<%= @homeworks.to_json %>]
        }]
    });

I tried changing action to this:

  def student_feedback
            difficulty_ids = current_user.school_user.homework_students.pluck(:difficulty)
            @homeworks = HomeworkStudent.where(["homework_id = ?", difficulty_ids]).first
        end

I keep getting this error:

Mysql2::Error: Operand should contain 1 column(s): SELECT `homework_students`.* FROM `homework_students` WHERE (homework_id = (4,2,1,2,3)) ORDER BY `homework_students`.`id` ASC LIMIT 1

The data being collected is correct. Though it says "homework_id = 4,2.." (this is not correct, those are the difficulty values). I suspect this is just a syntax error. I have toyed around a little bit. Can provide more code if needed.

I understand the problem but it's just the syntax...

Much appreciate any help. Thanks

UPDATE: Some progress...

      },
series: [{
    pointInterval: <%= 1.day * 1000 %>,
    pointStart: <%= 3.weeks.ago.at_midnight.to_i * 1000 %>,
    name: 'Difficulty',
    data: <%= Homework.get_difficulty.to_json %>
     },

In my homework.rb model:

def self.get_difficulty
      HomeworkStudent.pluck(:difficulty)
    end

This produces:

But this is obviously for all records whereas I only want current user's to show and I don't know how to get the dates set up properly (updated_at attribute).

回答1:

I think your SQL is wrong, try "homework_id in (?)" instead of homework_id = (?), to select rows with multiple values.

Your code should be:

def student_feedback
    difficulty_ids = current_user.school_user.homework_students.pluck(:difficulty)
    @homeworks = HomeworkStudent.where(["homework_id in (?)", difficulty_ids]).first
end