ruby on rails - Do I need to create an assocation table for a :has_many :through association? -
i'm trying use :has_many :through
type association, i'm getting following error:
activerecord::statementinvalid: sqlite3::sqlexception: no such column: work_units.developer_id:
many other posts sort of thing have had spelling mistakes, i've checked mine.
class developer < activerecord::base attr_accessible :skype_name, :language_ids, :user_attributes has_many :work_units has_many :projects, :through => :work_units ... end class project < activerecord::base attr_accessible :complete, :description, :finalised, :price has_many :work_units has_many :developers, :through => :work_units ... end class workunit < activerecord::base attr_accessible :hours_worked belongs_to :project belongs_to :developer end
i've run db:migrate
, didn't complain. did make mistake , had rollback db re-migrate, think did right. use annotate
gem , doesn't show of relationship ids i'd expect. so, need create workunits table or missing something? rails guide didn't mention manually making tables.
edit
here's migration used create workunit model , stuff:
class createworkunits < activerecord::migration def change create_table :work_units |t| t.integer :hours_worked, :default => 0 t.timestamps end end end
edit 2
snippets schema.rb:
create_table "work_units", :force => true |t| t.integer "hours_worked", :default => 0 t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end create_table "projects", :force => true |t| t.string "description" t.decimal "price", :precision => 8, :scale => 2 t.boolean "complete", :default => false t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end
similarly :developers
. so, why doesn't migration add association information me?
you need add foreign keys work_units
table.
class createworkunits < activerecord::migration def change create_table :work_units |t| t.integer :hours_worked, :default => 0 t.integer :project_id, null: false t.integer :developer_id, null: false t.timestamps end add_index :work_units, :project_id add_index :work_units, :developer_id end end
another way:
class createworkunits < activerecord::migration def change create_table :work_units |t| t.integer :hours_worked, :default => 0 t.belongs_to :project t.belongs_to :developer t.timestamps end add_index :work_units, :project_id add_index :work_units, :developer_id end end
you can define these fields when generating model, they'll added migration automatically show in second snippet.
$ rails g model workunit hours_worked:integer project:belongs_to developer:belongs_to
hope helps.
Comments
Post a Comment