【发布时间】:2015-01-25 20:06:28
【问题描述】:
我有一个 has_many :fonctions 的工作模型,在我的工作模型中,我正在创建一种方法来为我提供与给定工作相比,所有工作中相似功能的数量。
例如:我想将我所有的工作与 Job1 进行比较,job1 有这个功能(“战略”、“管理”、“营销”、“创业”) 另一份工作job2有这个功能(“战略”、“管理”、“数据科学”)
所以这必须给我做 (job1 & job2).size 2
为此,我的工作模型中有这个方法,它必须做类似的工作,但问题是我收到此错误undefined local variable or method for job'
def fonctions_score
(job.fonctions.collect(&:id) & self.fonctions.collect(&:id)).size
end
更新
这是我现在正在尝试但仍然收到此错误wrong number of arguments (0 for 1)的代码
def fonctions_score(other_job)
these = other_job.fonctions.collect {|f| f.id }
those = self.fonctions.collect {|f| f.id }
logger.debug these logger.debug those # should just have lists of ids
common = (these & those)
logger.debug common # should be common ids
common.size
end
在我的控制器中,我正在订购这样的工作
@related_jobs = Job.all
@related_jobs.sort_by do |related_job|
related_job.final_score
end
【问题讨论】:
-
如果这是 Job 类中的一个方法,那么你的 fonctions_score 方法中的 'job' 是未定义的。它不是自我,也不是类(应该是 Job)。您需要通过工作才能与自我进行比较。 def fonctions_score(other_job),然后将 self 与 other_job 进行比较。或类似的东西。
-
所以你建议我这样做 def fonctions_score(other_job) (other_job.fonctions.collect(&:id) & self.fonctions.collect(&:id)).id).size结束,但这会引发此错误错误数量的参数(0 代表 1)
-
堆叠或内联功能通常会隐藏问题。试试:这些 = other_job.fonctions.collect {|f| f.id } 那些 = self.fonctions.collect {|f| f.id } logger.debug 这些 logger.debug 那些 # 应该只有 id 列表 common = (these & those) logger.debug common # 应该是常见的 id common.size
-
我仍然收到同样的错误错误的参数数量(0 代表 1)为 def fonctions_score(other_job)
-
需要更多上下文。使用有关如何调用所有这些的代码更新您的问题 - 错误非常简单(我认为)。
标签: ruby-on-rails ruby ruby-on-rails-4 associations overlap