【问题标题】:Rails 3 has_many :through is only adding id from on side of the relationshipRails 3 has_many :through 只是从关系的一侧添加 id
【发布时间】: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,它的projectuser 值是多少?如果其中任何一个显示为零,请尝试collab(true).project 等,这会强制它重新加载。这有帮助吗?
  • 刚刚尝试过,我得到了相同的结果 :( 这是我检查协作时显示的内容(注意 user_id:nil)。#

标签: ruby-on-rails many-to-many has-many-through


【解决方案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,以及您尝试执行的&lt;&lt;。有关has_and_belongs_to_many 工作原理的进一步说明,以及您可以对关联使用的各种方法,请参阅Rails docs

【讨论】:

  • 对,我只是尝试做 has_many :through 以防我以后在协作中需要更多的灵活性。我还是会试试这个方法,看看能不能得到结果
  • 这就像一个魅力!如果我以后需要在加入中进一步灵活,我会处理它然后我猜.. 但它仍然困扰我为什么它不能与 has_many 一起工作:通过
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多