我想预览保存时模型的外观,但当前未保存到数据库。
我正在使用 @event.attributes =
因为它会将 @event
的属性分配但不会保存到数据库。
但是,当我还尝试分配 audiences
关联时,Rails 将新记录插入到 audiences_events
连接表中。不酷。有没有办法在不插入连接表的情况下预览这些新关联的外观?
型号
class Event < ActiveRecord::Base
has_and_belongs_to_many :audiences # And vice versa for the Audience model.
end
Controller
class EventsController < ApplicationController
def preview
@event = Event.find(params[:id])
@event.attributes = event_params
end
private
def event_params
params[:event].permit(:name, :start_time, :audiences => [:id, :name]
end
end
可能的解决方案?
我想到但不知道怎么做的可能解决方案:
- 使用某种方法来分配关联,但不会持久化它们。
- 为此操作禁用所有数据库写入(我不知道该怎么做)。
- 在此操作结束时回滚所有数据库更改
任何有关这些的帮助都会很棒!
更新:
阅读下面的精彩答案后,我最终编写了这个服务类,它将非嵌套属性分配给事件模型,然后在每个嵌套参数上调用 collection.build。我做了一个小要点。很高兴收到评论/建议。
最佳答案
在这些docs你有:
When are Objects Saved?
When you assign an object to a has_and_belongs_to_many association, that object is automatically saved (in order to update the join table). If you assign multiple objects in one statement, then they are all saved.
If you want to assign an object to a has_and_belongs_to_many association without saving the object, use the
collection.build
method.
这是 Rails 3 的一个很好的答案,它解决了一些相同的问题
关于ruby-on-rails - Rails 预览更新关联而不保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30109549/