簡體   English   中英

Ruby on Rails:使用has_many:through關聯進行過濾

[英]Ruby on Rails : Filter with has_many :through Association

我的index.html.erb中有一個表單,我想用“合格”表過濾項目。 has_many:through association怎么辦? 我在控制器中寫了一個請求,但不起作用。

非常感謝您的建議!

型號: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

控制器: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

查看: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>

解決方案是:

 request = request.joins(:project_eligibles).where(project_eligibles: {eligible_id: session[:search]['eligible']}) if session[:search]['eligible'].present?

不是: request = request.joins(:eligibles).where(eligibles: session[:search]['eligibles']) if session[:search]['eligibles'].present?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM