has_many /:通过rails4

时间:2015-10-21 13:01:30

标签: ruby-on-rails ruby-on-rails-4 model-view-controller has-many-through

我已经在其他技术上长时间回到轨道上,看起来我有点生疏。

我一直在尝试处理Project,Client和Contact,我对结果感到有些困惑。

起初我的项目中只有一个“contact_id”,一切都找到了,但我发现我真的很想拥有一个项目的多个联系人。

所以这就是我一直在尝试的:

项目模型:

class Project < ActiveRecord::Base
  belongs_to :owner, class_name: User, foreign_key: "owner_id"
  belongs_to :worker, class_name: User, foreign_key: "worker_id"
  #  belongs_to :contact, class_name: Contact, foreign_key: "contact_id"
  has_many :project_contacts
  has_many :contacts, :through => :project_contacts
  has_many :tasks
  has_many :feedbacks
  before_save :set_estimated_time
  #pleinty of utilities
end

联系模式:

class Contact < ActiveRecord::Base
  belongs_to :client, class_name: Client, foreign_key: "client_id"
  has_manny :project_contacts
  has_many :projects, :through => :project_contacts
end

ProjectContact模型:

class ProjectContact < ActiveRecord::Base
  belongs_to :project
  belongs_to :contact
end

我认为没关系,但这是我使用Rails控制台时得到的结果:

  

2.2.3:001&gt; project = Project.find(31)         项目负载(0.3ms)SELECT'project'。* FROM'projects'WHERE'projects''id'= 31 LIMIT 1        =&GT; #       2.2.3:002&gt; project.contacts       NameError:未初始化的常量Project :: ProjectContact

编辑:

联系人迁移

class AddProjectContacts < ActiveRecord::Migration
  def change
    create_table :project_contacts do |pc|
      pc.belongs_to :project, index: true
      pc.belongs_to :contact, index: true
      pc.timestamps null: false
    end
  end
end

我非常感谢您对此的任何帮助

再见

3 个答案:

答案 0 :(得分:1)

您在class Contacthas_many而非has_manny中输入了拼写错误。

答案 1 :(得分:1)

好的,所以我只是将班级名称更改为“参与者”尝试,一切都很好。 : - |

答案 2 :(得分:1)

对于后人来说,这就是我期望的样子:

#app/models/project.rb
class Project < ActiveRecord::Base
   has_many :project_contacts
   has_many :contacts, through: :project_contacts
end 

#app/models/project_contact.rb
class ProjectContact < ActiveRecord::Base
   #columns id | project_id | contact_id | created_at | updated_at
   belongs_to :project
   belongs_to :contact
end

#app/models/contact.rb
class Contact < ActiveRecord::Base
   has_many :project_contacts
   has_many :projects, through: :project_contacts
end

这应该可以让你调用:

@project = Project.find params[:id]
@project.contacts #-> shows all contacts