我正在做一个在线单词学习项目,我想提供一个搜索功能,您可以在其中按课程,单词和学习状态(已学习/未学习)过滤单词。完成课程和单词的过滤。我陷入了最后的过滤条件。我正在使用作用域,但学习状态的参数似乎无法进入作用域,“ words”表和“ user_words”表将无法连接(我首先尝试了这两个表)。
这是我的桌子:
create_table "users" do |t|
t.string "username"
end
create_table "words" do |t|
t.string "name"
t.integer "lesson_id"
end
create_table "user_words" do |t|
t.integer "user_id"
t.integer "word_id"
t.boolean "status"
end
我的模型:
class User < ApplicationRecord
has_many :user_words
end
class Word < ApplicationRecord
has_many :user_words
scope :order_name_asc, -> {order name: :asc}
scope :search_prefix, -> prefix {where "name like ?", "#{prefix}%"}
scope :search_lesson, -> lesson_id {
where("lesson_id = ?", lesson_id) if lesson_id.present?}
# Is the problem here?
scope :search_learned, -> (learned) do
joins(:user_words).where("user_words.status = ?",
learned[:user_word_status].to_i) if learned[:user_word_status]
end
end
class UserWord < ApplicationRecord
belongs_to :user
belongs_to :word
end
我的控制器
class StaticPagesController < ApplicationController
before_action :load_lessons, only: :home
before_action :load_user_words, only: :home
def home
@words = Word.search_learned(learned: params[:learned]) #or the problem's here
.search_lesson(params[:lesson_id])
.search_prefix(params[:prefix]).order_name_asc
.paginate page: params[:page]
end
end
和视图:
# Lesson filter option:
<%= select_tag :lesson_id,
grouped_options_for_select(@categories.map {|category|
[category.name,category.lessons.map {|lesson| [lesson.name,
lesson.id]}]}),
include_blank: t(".all_lessons"), class: "btn btn-primary" %>
# Learning status filter option (is the problem here?):
<%= select_tag :learned,
options_for_select(@user_words.map(&:status)),
include_blank: t(".learned"), class: "btn btn-secondary" %>
# Text input fied, submit button and the word list:
<%= text_field_tag :prefix, params[:prefix],
placeholder: t(".search"), class: "form-control" %>
<%= submit_tag t(".search"), name: nil, class: "btn btn-success" %>
<% @words.each do |word| %>
<%= link_to word.name, "#" %>
<% end %>