繁体   English   中英

Rails:通过关联过滤has_many

[英]Rails: filtering in has_many through association

我正在使用滑轨,我有这个模型

Job
  has_many :job_fonctions
  has_many :fonctions, through: :job_fonctions

JobFonction 
    belongs_to :job
    belongs_to :fonction 

Fonction
    has_many :job_fonctions
    has_many :jobs, through: :job_fonctions

我想要的是在显示页面上对与当前作业具有相同功能的所有作业进行排序,我已经在控制器中尝试了此代码

@related_jobss = Job
    .where('jobs.id != ?', @job.id)
    .where(:fonction_id=>@job.fonction)

但这给了我这个错误的undefined method fonction'for`,所以我想知道如何去做?

这是我的查看代码

<% @related_jobs.each do |job| %>
    <%= link_to truncate(job.job_title, length: 45, escape: false).html_safe, job%>
<% end %>

通过创建一个新类来处理此逻辑,您会获得更好的体验。 在模型目录中执行类似的操作,或创建一个自动加载的新服务目录。

#in controller, @fonction can be any Fonction object
@related_jobss = RelatedJobFinder.new(@job, @fonction).with_same_fonction


#this would be in it's own file related_job_finder.rb
class RelatedJobFinder

  def initialize(job, fonction)
    @job = job
    @fonction = fonction
  end

  def with_same_fonction
    remove_this_job_from(jobs)
  end

  private

  def jobs
    Fonction.find(@fonction.id).jobs
  end

  def remove_this_job_from(relation)
    relation.reject{|job| job.id == @job.id}
  end

end

编辑

尝试这个:

@related_jobss = 
Job.includes(:fonctions)
.where('jobs.id != ?', @job.id)
.where(fonctions: { id: @job.fonctions.pluck(:id) } ) 

这应该给你的所有Jobs与fonctions在作业不等于@job和具有的与任何fonctions(一个,两个或全部) @job.fonctions

我刚刚在我的应用程序中测试了此方法的相关性(我正在运行Rails 4.1.6 FYI),并且我取出了与我列出的ID的总数组仅部分匹配的项目。

暂无
暂无

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

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