Rails 4有很多通过

Rails 4 has many through

您好,我是 rails 新手,我很难理解我遇到的错误。

我有多对多关系,由

组成
  1. 项目 -> 一对多 project_numbers(帐单编号)
  2. project_number -> 具有与任务关联的 ID、project_id(fk)、task_name 和小时数。
  3. 助理-> Employee/Developer 执行工作(id、姓名、...)
  4. 资源 -> 加入 table 包含 ID,project_number_id (fk) 和 Associate_id (fk),分配的小时数,使用的小时数

我的模型如下

#project.rb
class Project < ActiveRecord::Base
  database_connection = Rails.env
  establish_connection database_connection.to_sym
  self.table_name = 'projects'
  belongs_to :client, :inverse_of => :project
  has_many :project_numbers
end

#associate.rb
class Associate < ActiveRecord::Base
  database_connection = Rails.env
  establish_connection database_connection.to_sym
  self.table_name = 'associates'
  has_many :resources
  #has_many :project_numbers, through: => :resources
end

#project_number.rb
class ProjectNumber < ActiveRecord::Base
  database_connection = Rails.env
  establish_connection database_connection.to_sym
  self.table_name = 'project_numbers'
  belongs_to :project, :inverse_of => :project_number
  has_many :resources
  #has_many :associates, through: => :resources
end

resource.rb
class Resource < ActiveRecord::Base
  database_connection = Rails.env
  establish_connection database_connection.to_sym
  self.table_name = 'resources'
  belongs_to :project_number
  belongs_to :associate
end

每次我取消注释 "has_many through" 行时,我在查看项目详细信息页面(显示)时收到错误消息:

我的 show.html.erb 有一行突出显示

    <dt>Project Hours: </dt> <dd><%= @project.project_numbers.sum(:hours_sold)%></dd>

rails 错误: /home/ruby/pda/app/models/project_number.rb:7: 语法错误,意外 => has_many :associates, 通过: => :resources

我浏览了很多博客,认为我已经正确设置了关系,但我根本不明白其中的错误。为什么在 project_number 中调用 sum(hours) 会触发此错误。注意:即使注释了这一行,下一个针对 project_numbers 的查询也会失败。有人可以帮助我了解我所缺少的吗?

这行语法错误。

has_many :project_numbers, through: => :resources #wrong

这是正确的语法

has_many :project_numbers, :through => :resources # right

对于Rails4,可以写成

has_many :project_numbers, through: :resources

对另一个协会也做同样的更改。