ruby-on-rails – 使用collection_singular_ids = ids而不保存到
发布时间:2020-12-17 02:19:32 所属栏目:百科 来源:网络整理
导读:在rails中,我使用other_ids = […]方法在has_many:through关联上分配连接.它工作正常,除非我不想将other_ids = […]提交到数据库(使用此方法分配自动保存). 有没有办法在使用Model.new时分配这些连接?这有用的一个例子是当我提交一个包含has_many关系复选
在rails中,我使用other_ids = […]方法在has_many:through关联上分配连接.它工作正常,除非我不想将other_ids = […]提交到数据库(使用此方法分配自动保存).
有没有办法在使用Model.new时分配这些连接?这有用的一个例子是当我提交一个包含has_many关系复选框的表单时.当表单未保存时(验证失败时),所选复选框将重置. 模型: class Job < ActiveRecord::Base has_many :categories attr_accessible :category_ids end 视图: select :category_ids,Category.all.collect {|x| [x.name,x.id]},{},{:multiple => true} 解决方法
那很奇怪.我的意思是,我理解为什么它会保存,因为它是其他记录的关系,而不是你正在使用它的那个,但我认为应该很容易在AR中实现该功能.
无论如何,你可以做以下的事情来解决这个问题.使用虚拟属性 class Bar < ActiveRecord::Base after_save :save_foos has_many :foos attr_accessor :temp_foo_ids # Bad name for it but whatever... attr_accessible :temp_foo_ids def save_foos foo_ids = temp_foo_ids # it should save the record like this again right? end end 在视图中,您还将使用虚拟属性 select :temp_foo_ids,Foo.all.collect {|x| [x.name,{:multiple => true} 我没有测试过这个,但我相信它会起作用;) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |