Rails 更新多对多记录
我在尝试更新现有的多对多记录时陷入困境。
项目模型:
class Project < ActiveRecord::Base
belongs_to :assignment
belongs_to :programmer
end
程序员模型:
class Programmer < ActiveRecord::Base
has_many :projects
has_many :assignments, :through => :projects
end
作业模型:
class Assignment < ActiveRecord::Base
has_many :projects
has_many :programmers, :through => :projects
end
所以我有这样链接的数据:
p = Programmer.create(:name => "Mike")
p.assignments.create(:name => "homework4")
p.assignments[0] = Assignment.find_or_create_by_name("homework1")
p.save
如您所见,我正在尝试将 Mike 的第一个硬件的关联更新为“homework1”。所有作业都已在作业表中,因此只需找到“homework1”并将其分配给 mike。不幸的是,当我输入第三行时没有错误,但它没有更新它。在内存中,p.assignments == homework1
,但在数据库中它仍然是相同的(即使在 p.save 之后)。项目的连接表根本没有改变。
mysql 的日志显示每当我输入第三行时就会生成此命令。
SELECT "assignments".* FROM "assignments" WHERE "assignments"."name" = 'homework1' LIMIT 1
任何地方都没有更新......我做错了什么?
更新
所以我发现我可以直接引用联接表来编辑链接。大致如下:
proj = p.projects.first
proj.assignment_id = 12
proj.save!
I'm getting stuck at trying to update an existing many to many record.
Project model:
class Project < ActiveRecord::Base
belongs_to :assignment
belongs_to :programmer
end
Programmer model:
class Programmer < ActiveRecord::Base
has_many :projects
has_many :assignments, :through => :projects
end
Assignment model:
class Assignment < ActiveRecord::Base
has_many :projects
has_many :programmers, :through => :projects
end
so I have data linked up like so:
p = Programmer.create(:name => "Mike")
p.assignments.create(:name => "homework4")
p.assignments[0] = Assignment.find_or_create_by_name("homework1")
p.save
so as you can see, I'm trying to update the association of Mike's first hw to "homework1". All the homework assignments are already in the assignments table so it shoud just find "homework1" and assign it to mike. unfortunately, when I type the third line there are no errors, but it doesn't update it. In memory, p.assignments == homework1
, but in the DB it's still the same(even after p.save). The project's join table isn't changed at all.
the logs of mysql show this command being generated whenever I enter the 3rd line.
SELECT "assignments".* FROM "assignments" WHERE "assignments"."name" = 'homework1' LIMIT 1
there's no Update anywhere.... what am I doing wrong?
UPDATE
So I found out that I could just reference the join table directly to edit the links. Something along the lines of:
proj = p.projects.first
proj.assignment_id = 12
proj.save!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您只想引用该对象,那么您需要编辑迁移脚本 (db/migrate)。一个例子:
不要忘记输入:
If you just want a reference to the object, then you need to edit your migration scripts (db/migrate). An example:
Don't forget to type: