【发布时间】:2015-01-27 16:07:41
【问题描述】:
我正在使用 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 methodfonction'for`,所以我想知道该怎么做?
这是我的视图代码
<% @related_jobs.each do |job| %>
<%= link_to truncate(job.job_title, length: 45, escape: false).html_safe, job%>
<% end %>
【问题讨论】:
-
因为是has_many关系,所以方法调用是
@job.fonctions而不是@job.fonction,它会返回所有与@job相关的函数(不是单个id)。你想匹配@job 的所有功能还是只匹配一个?此外,fonction_id 应该在 JobFonction 中,而不是 Job,因此一旦您知道要查找的 fonction id/id,您将在 JobFonction 中查找它们以找到相应的 Jobs。 -
我想匹配至少一个函数
-
在控制台尝试:
@job.fonctions.first.jobs。这应该会为您提供与@job 关联的第一个函数关联的所有作业的列表。
标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 associations