简体   繁体   English

Ransack:has_many通过协会期待param抛出错误

[英]Ransack: has_many through association expecting param throws error

Here's a generic approximation of my models, with a has_many through using a scope that expects a parameter 这是我的模型的一般近似,通过使用需要参数的范围来使用has_many

class GlobalCompany
  has_many :locations
  has_many :global_company_forms, :through => :locations
end

class Location
  belongs_to :global_company
  has_one :global_company_form
end

class Company
  belongs_to :global_company
  belongs_to :subdomain

  has_many :global_company_forms, ->(company) { for_company(company) }, :through => :global_company
end

class GlobalCompanyForm
  belongs_to :location
  belongs_to :subdomain_form

  scope :for_company, ->(company) {where(:subdomain_form_id => company.subdomain.subdomain_form.id)}
end

class SubdomainForm
  belongs_to :subdomain
end

Company.ransack(q).result will throw: Company.ransack(q).result将抛出:

NoMethodError: undefined method `subdomain' for #<ActiveRecord::Associations::JoinDependency::JoinAssociation:0x007fbd227f0850>

when ransack accesses that association its passing in an association as the 'company', instead of a company record, hence the no method 当ransack访问该关联时,它将其作为“公司”传递给关联,而不是公司记录,因此是no方法

I've looked around, but haven't found any similar examples and I cannot figure out how to make ransack respect this type of association/scope. 我环顾四周,但没有找到任何类似的例子,我无法弄清楚如何进行搜索,尊重这种类型的关联/范围。 The association itself works fine outside of ransack. 该协会本身在洗劫之外工作正常。

You just have to perform the join manually in your controller when specifying the table to draw results from: 您只需在控制器中手动执行连接,同时指定要从以下位置绘制结果的表:

@q= GlobalCompany.joins(:location, :global_company_forum).ransack(params[:q])

And when set up the form, use: 在设置表单时,使用:

<%=f.search_field :global_company_forum_name_contains%>

And for results, just chain the models together: 为了获得结果,只需将模型链接在一起:

global_company_instance.location.global_company_forum.name

I developed this based on a discussion here . 我根据这里的讨论开发了这个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM