I have a form in my index.html.erb and i would like to filter the projects with the "eligibles" table. How can I do with has_many :through association ? I wrote a request in my controller but it doesn't work.
Thank you very much for your advice !
MODEL: Project_eligible.rb
class ProjectEligible < ApplicationRecord
belongs_to :project
belongs_to :eligible
end
project.rb
class Project < ApplicationRecord
has_many :project_eligibles
has_many :eligibles, through: :project_eligibles
scope :eligibles, -> (eligibles) { where eligibles: eligibles }
end
eligible.rb
class Eligible < ApplicationRecord
has_many :project_eligibles
has_many :projects, through: :project_eligibles
end
CONTROLLER: project_controller.rb
def index
@search = Search.new(search_params)
@eligibles = Eligible.all
session[:search] = params[:search] if params[:search].present?
request = Project
return @projects = request.page(params[:page]).order("expiration ASC").paginate(:page => params[:page], :per_page => 2) unless session[:search].present?
request = request.joins(:eligibles).where(eligibles: session[:search]['eligibles']) if session[:search]['eligibles'].present?
@projects = request.page(params[:page]).order("expiration ASC").paginate(:page => params[:page], :per_page => 2)
end
private
def search_params
if params[:search].present?
p = params.require(:search).permit!
session[:search] = p
else
session[:search]
end
end
VIEW: Index.html.erb
<div class="form-inputs" id="form">
<%= simple_form_for @search, method: :get, url: projects_path do |f| %>
<div>
<%= f.input :eligible, :include_blank => "Tous publics", required: false, label: false, collection: @eligibles, class: 'form-control' %>
</div>
<div>
<%= f.submit 'GO', class: 'btn btn-primary paddind-category btn-from-search' %>
</div>
<% end %>
</div>
The solution is:
And not:
request = request.joins(:eligibles).where(eligibles: session[:search]['eligibles']) if session[:search]['eligibles'].present?