我想從has_many,belongs_to關係移動到has_many:通過與我的項目和用戶模型的關係。但是,當我在rails控制檯中測試它時,只有關係的一方似乎在連接模型中設置。Rails 3 has_many:通過只是從關係端添加ID
我現在有它成立這樣的:
class Project < ActiveRecord::Base
has_many :collaborations
has_many :users, :through => :collaborations
end
class User < ActiveRecord::Base
has_many :collaborations
has_many :projects, :through => :collaborations
end
class Collaboration < ActiveRecord::Base
belongs_to :project
belongs_to :user
end
然後在控制檯我打字在:
me = User.find(1)
p = Project.new(:name => "somename")
p.users << me
p.save
會發生什麼是協作模型得到PROJECT_ID設置,但不是user_id。
而相反的情況(user_ID的獲取但未設置PROJECT_ID),當我做這樣的事情:
me.projects << p
基本上,它會創建一個「協作」,但只有一個關係的一側被保存。
我一直堅持這個小時,現在我覺得它是一些小事 - 也許是我在做這兩個模型之間的一對多關係時遺留下來的東西。
---編輯--- 這個模式看起來是什麼樣子:
create_table "collaborations", :force => true do |t|
t.integer "project_id"
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "projects", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
t.boolean "shared", :default => false
t.integer "position", :default => 0
t.string "permalink"
t.text "description"
end
create_table "users", :force => true do |t|
t.string "username"
t.string "email"
t.string "crypted_password"
t.string "password_salt"
t.string "persistence_token"
t.datetime "created_at"
t.datetime "updated_at"
t.string "role"
t.string "first_name"
t.string "last_name"
t.string "perishable_token", :default => "", :null => false
t.integer "avatar", :default => 0
end
任何幫助將非常感激!
您的模式對於項目,協作和項目來說是什麼樣的? – clemensp 2011-01-19 01:58:39
只是在那裏爲你添加 – Matt 2011-01-19 02:44:43