Rails has_and_belongs_to_many 总是插入到数据库中
这是我的问题:
class Facility < ActiveRecord::Base
...
has_and_belongs_to_many :languages, :autosave => false, :join_table => 'facilities_languages'
...
end
当我做这样的事情时:
facility = Facility.find(1)
language = Language.find(1)
facility.languages << language
Rails 总是执行 SQL 请求:
"INSERT INTO `facilities_languages` (`language_id`,`facility_id`) VALUES (1, 1)"
有没有办法避免数据库请求,除非我调用 'facility.save' ?
显然, :autosave 选项在这里还有其他作用。
Here is my problem:
class Facility < ActiveRecord::Base
...
has_and_belongs_to_many :languages, :autosave => false, :join_table => 'facilities_languages'
...
end
When I do something like this:
facility = Facility.find(1)
language = Language.find(1)
facility.languages << language
Rails always do the SQL request:
"INSERT INTO `facilities_languages` (`language_id`,`facility_id`) VALUES (1, 1)"
Is there a way to avoid database requests unless I call 'facility.save' ?
Apparently, :autosave option here does something else.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的问题是您使用的
has_and_belongs_to_many
不是基于Model
的,因此您无法将其作为对象访问。您可以创建一个执行关联的模型
,然后您可以创建该关联模型的新对象。例如:在模型中
在其他模型中:
Faculty
Language
那么您将能够通过创建不自动保存的关联对象来添加关联。例如,您有一个包含 ids 的
String
,其中包含应在FacultyController
中名为language_ids
关联的语言对象的 id:代码应该在系统保存后进行调整和定位。
Your Problem is that you use
has_and_belongs_to_many
which isnt based on aModel
so you cant access it as an Object. You could create aModel
that is doing the associations and then you could create new objects of this association model. e.g.:In the Model
In the other models:
Faculty
Language
Then you would be able to add associations by creating association objects which arent saved automaticly. For example you have a
String
containing ids that contains the ids of the language objects which should be associated calledlanguage_ids
in theFacultyController
:Of cause this code should be conditioned and positioned after the save of faculty.
如果您使用铲子操作符<< Rails 自动保存关联的对象。
从文档中
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods。 html
If you use the shovel operator << Rails automatically saves the associated object.
From the documentation
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
设施.语言 = [语言]
facility.languages = [language]