Using Rails 4 and Ruby 2.2, I have Subject list page where I need to add the filter for subject's name, username, active and books associated with the subject. All the three model i.e
Subject, Book and User
are associated as below:
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
Now I am trying to make filter on the subject list page with the following column
- Username(Drop Down from User table)
- Subject name(text field from subject table)
- Active(Drop Down from subject table)
- Has books (Radio button, association with books)
I have my index for subject as follows:
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
and my
index.html.erb
as:
<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>
Questions:
- How can I have username column associated with each book in filter list
- How to make filter list for has books or not as radio button?
- How the active for subject(boolean datatype) list will work ?
Let me know if I need to provide more details
Aucun commentaire:
Enregistrer un commentaire