Rails:通过关联过滤has_many

时间:2014-11-29 02:03:21

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

我使用rails并且我有这个模型

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 %>

2 个答案:

答案 0 :(得分:1)

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

#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

答案 1 :(得分:0)

修改

试试这个:

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

这应该为所有Jobs提供作业不等于@job并且具有与@job.fonctions相同的任何功能(一,二或全部)的功能。

我刚刚在我的应用程序中测试了这个方法(我运行Rails 4.1.6 FYI),并且我提取了与我列出的id总数部分匹配的项目。