2011-01-19 57 views
1

我想從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 

任何幫助將非常感激!

+0

您的模式對於項目,協作和項目來說是什麼樣的? – clemensp 2011-01-19 01:58:39

+0

只是在那裏爲你添加 – Matt 2011-01-19 02:44:43

回答

1

這聽起來像你試圖建立一個迂迴的has_and_belongs_to_many關係。您的Collaboration模型看起來完全像連接模型。

我建議與適當的has_and_belongs_to_many關係。基本上,你會變成什麼樣:

class Project < ActiveRecord::Base 
    has_and_belongs_to_many :users 
end 

class User < ActiveRecord::Base 
    has_and_belongs_to_many :projects 
end 

然後你需要創建一個連接表遷移:

def self.up 
    create_table :projects_users, :id => false do |t| 
    t.references :project, :user 
    end 
end 

def self.down 
    drop_table :projects_users 
end 

然後,您應該能夠做到User.find(123).projectsProject.find(321).users,以及作爲<<你想要做的。有關has_and_belongs_to_many如何工作的進一步說明以及可用於關聯的各種方法,請參閱Rails docs