Rails 4 has_many through

时间:2015-03-10 02:29:43

标签: ruby-on-rails-4 activerecord rails-activerecord

大家好,我是铁杆新手,很难理解我遇到的错误。

我有很多关系,包括

  1. 项目 - >一对多project_numbers(帐单号码)
  2. project_number - >具有id,project_id(fk),task_name和与任务相关联的小时数。
  3. Associate->员工/开发人员执行工作(身份证,姓名,......)
  4. 资源 - >加入包含ID,project_number_id(fk)和Associate_id(fk)的表,分配的小时数,使用的小时数
  5. 我的模型如下

    #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
    

    每次我取消注释&#34; has_many到&#34;我收到错误查看项目详情页面(显示):

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

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

    导轨错误: /home/ruby/pda/app/models/project_number.rb:7:语法错误,意外=&gt;   has_many:associates,through:=&gt; :资源

    我经历了很多博客,并认为我已经正确设置了关系,但我根本不理解错误。为什么在project_number中调用sum(hours)会导致触发此错误。注意:即使使用此行注释,针对project_numbers的下一个查询也会失败。有人可以帮我理解我错过的东西吗?

1 个答案:

答案 0 :(得分:1)

这一行在语法上是错误的。

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

这是正确的语法

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

对于 Rails4 ,您可以将其写入

has_many :project_numbers, through: :resources

对其他协会也进行相同的更改。