使用Rails 4和Ruby 2.2,我有主题列表页面,我需要为主题的名称,用户名,活动和与主题相关的书籍添加过滤器。所有三个模型,即
主题,书籍和用户
关联如下:
user.rb
class User < ActiveRecord::Base
has_many :subjects, dependent: :destroy
has_many :books, dependent: :destroy
end
book.rb
class Book < ActiveRecord::Base
belongs_to :subject, dependent: :destroy
belongs_to :user, dependent: :destroy
has_many :images, dependent: :destroy
end
subject.rb中
class Subject < ActiveRecord::Base
belongs_to :user
has_many :books
validates :name, presence: true,
length: { minimum: 3 }
def self.names(name)
subject = all
subject = subject.where("name LIKE ?", "%#{name}%")
return subject
end
def self.actives(active)
subject = all
subject = subject.where("active = ?", "%#{active}%")
return subject
end
def self.usernames(username)
user = all
user = user.where("username LIKE ?", "%#{username}%")
return user
end
end
现在我正尝试使用以下列
在主题列表页面上进行过滤
- 用户名(从用户表下拉)
- 主题名称(主题表中的文本字段)
- 有效(从主题表下拉)
- 有书(复选框,与书籍的关联,如果选中,只显示那些有书籍的科目)
醇>
我的主题索引如下:
subjects_controller.rb
def index
@subjects = Subject.page(params[:page]).per(10)
@users = User.all
@subjects = @subjects.names(params[:name]) if params[:name].present?
@subjects = @subjects.actives(params[:active]) if params[:active].present?
@users = @users.usernames(params[:username]) if params[:username].present?
end
和我的
index.html.erb
为:
<h1>Listing Subjects</h1>
<%= link_to 'New Subject', new_subject_path %>
<%= form_tag subjects_path, :method=> "get" do %>
<%= label_tag :username, "Username" %>
<%= select_tag :username, options_from_collection_for_select(User.all, "id", "username", username) %>
<%= label_tag :name, "Subject Name"%>
<%= text_field_tag :name %>
<%= label_tag :active, "Active" %>
<%= select_tag :active, options_for_select([['Active', true], ['Inactive', false]]) %>
<%= submit_tag "submit" %>
<%= link_to "Clear Search", request.path, class:"cancel-button" %>
<% end %>
<div id="subjects"><%= render "index" %></div>
<%= paginate @subjects %><br>
我的控制台日志如下:
Started GET "/subjects?utf8=%E2%9C%93&username=11&name=&active=false&commit=submit" for ::1 at 2016-04-19 10:20:06 +0530
Processing by SubjectsController#index as HTML
Parameters: {"utf8"=>"✓", "username"=>"11", "name"=>"", "active"=>"false", "commit"=>"submit"}
User Load (0.4ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = ? ORDER BY `users`.`id` ASC LIMIT 1 [["id", 11]]
User Load (0.6ms) SELECT `users`.* FROM `users`
Subject Load (0.5ms) SELECT `subjects`.* FROM `subjects` WHERE (active = '%false%') LIMIT 10 OFFSET 0
Rendered subjects/_index.html.erb (5.1ms)
(0.5ms) SELECT COUNT(*) FROM `subjects` WHERE (active = '%false%')
Rendered subjects/index.html.erb within layouts/application (34.9ms)
Completed 200 OK in 99ms (Views: 94.1ms | ActiveRecord: 2.1ms)
问题:
如果我需要提供更多详情,请告诉我