【发布时间】:2011-06-11 11:41:22
【问题描述】:
我正在尝试从 has_many, belongs_to 关系转移到 has_many :through 与我的项目和用户模型的关系。但是,当我在 Rails 控制台中对其进行测试时,似乎只有一侧关系在连接模型中设置。
我目前的设置是这样的:
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
任何帮助将不胜感激!
【问题讨论】:
-
您的项目、协作和项目的架构是什么样的?
-
刚刚为你添加了它
-
抱歉——我的意思是,如果您使用
collab = Collaboration.last,它的project和user值是多少?如果其中任何一个显示为零,请尝试collab(true).project等,这会强制它重新加载。这有帮助吗? -
刚刚尝试过,我得到了相同的结果 :( 这是我检查协作时显示的内容(注意 user_id:nil)。#
标签: ruby-on-rails many-to-many has-many-through