0
我想遍歷所有用戶的答案,並通過回答收到的喜歡數量來排序,但我無法弄清楚如何去做,@ user.answers.likes不起作用,我找到了一種方法找到所有用戶喜歡的答案,但這不完全是我想要做的。感謝您的幫助。如何通過點數來排序用戶的答案?
型號/ answer.rb
class Answer < ApplicationRecord
belongs_to :question
belongs_to :user
has_many :likes, dependent: :destroy
型號/ user.rb
class User < ApplicationRecord
has_many :answers
has_many :likes
型號/ like.rb
class Like < ApplicationRecord
belongs_to :user
belongs_to :answer
schema.rb
create_table "answers", force: :cascade do |t|
t.text "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "question_id"
t.integer "user_id"
t.boolean "accepted", default: false
t.index ["question_id"], name: "index_answers_on_question_id"
end
create_table "likes", force: :cascade do |t|
t.integer "user_id"
t.integer "answer_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
要小心,你打開一扇門,當你插一個字符串,SQL注入直接進入查詢 –
雖然這不是一種形式 - 沒有輸入注入。這只是一個查詢,所以他可以按用戶的喜好順序顯示答案。 – toddmetheny
是的,只是因爲這個「小心」,在這種情況下沒有問題,但我認爲在其他情況下這可能是一個漏洞。無論如何,Aleks並沒有告訴我們他們如何獲得'@ user',如果他以'@ user.id'可以改變的方式獲得''user',就會出現問題。這只是一個評論,如果我冒犯了你,很抱歉 –