如何在搜索方法中访问此联接表?

时间:2016-09-02 11:35:39

标签: ruby-on-rails ruby-on-rails-4

我的客户有很多地区,我的地区有很多客户。通过联接表Regionmemberships。

我想过滤我的客户,找到我在表单中点击的region_id。我可以让它在我的控制台中工作,但不能在我的应用程序中工作。

当我尝试在控制台中手动过滤它们时,以下代码有效。我想在search.rb模型中的find_results方法中使用类似或相同的方法,但看起来好像:regionmemberships未被识别为连接到我的客户端。

找到我想要的控制台代码:

results = Client.all
results = results.where(category_id: 3)
results = results.includes(:regionmemberships).where(“regionmemberships.region_id” => “1”)

但是,如果我在我的应用中尝试相同的操作,它会让我此错误

undefined local variable or method `“regionmemberships' for #<Search:0x007ffdd44e96c8>

并引用此错误:(:在错误文本中标记了regionmemberships)

def find_results
    results = Client.order(:name) 
    results = results.where(visible: true)
    results = results.where(category_id: category_id) if category_id.present?
    results = results.includes(:regionmemberships).where(“regionmemberships.region_id” => “0”)   

这就是我的应用的外观:

型号:

Client.rb
has_many :regionmemberships, :dependent => :destroy
has_many :regions, through: :regionmemberships
belongs_to :category

Region.rb
has_many :regionmemberships, :dependent => :destroy
has_many :clients, through: :regionmemberships

Regionmembership.rb
belongs_to :client
belongs_to :region

Category.rb
has_many :clients

我的new.html.erb 视图

中的相关表单
new.html.erb
<%= f.collection_select :region_id,
Region.all, :id, :name, {include_blank: false}, 
{class: "regionclass", size: "1"} %>

Searches_controller

  def new
    @search = Search.new

  def create
    @search = Search.create!(search_params)
    redirect_to @search 
  end

  def show
    @search = Search.find(params[:id])
  end

def search_params
    params.require(:search).permit(:category_id, :region, :regions, :regionmembership, :regionmemberships, :visible, :region_id, :pricerange1, :pricerange2, :pricerange3, :pricerange4, :pricerange5, region_ids: [])
end

Search.rb (这是我需要为我的控制台创建类似代码的示例 - 但看起来似乎:regionmemberships不存在/无法找到/引用)

class Search < ApplicationRecord
    def results
        @results ||= find_results
    end

private
    def find_results
        results = Client.order(:name) # Her skal ændres til position hvis visse clients ska
        results = results.where(visible: true)
        results = results.where(category_id: category_id) if category_id.present?
        results = results.includes(:regionmemberships).where(“regionmemberships.region_id” => “1”)    
    end
end

希望任何人都可以提供帮助!似乎我需要应用程序才能理解客户端连接到:regionmemberships列。谢谢!!

1 个答案:

答案 0 :(得分:0)

这段代码做到了!

results = results.joins(:regionmemberships).where('regionmemberships.region_id = ?', region_id)  

在这个帖子的帮助下: Rails joins query