I've been back on rails after long period on other techno, and it appears i'm a bit rusty.
I've been trying to handle Project, Client and Contact and I'm a little confused by the results.
At first I had just one "contact_id" in my Project and everything was find, but I figured out I'd really love to have multiple contacts for one project.
So this is what i've been trying :
Project model:
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
Contact model:
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 model:
class ProjectContact < ActiveRecord::Base
belongs_to :project
belongs_to :contact
end
I thought it was ok but here's what I get when I use Rails console:
2.2.3 :001 > project = Project.find(31) Project Load (0.3ms) SELECT 'projects'.* FROM 'projects' WHERE 'projects'.'id' = 31 LIMIT 1 => # 2.2.3 :002 > project.contacts NameError: uninitialized constant Project::ProjectContact
Edit :
Contact migration
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
I'd really appreciate any help with this
Bye
For posterity, here's how I'd expect it to look:
#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
This should give you the ability to call:
@project = Project.find params[:id]
@project.contacts #-> shows all contacts
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句