小编jke*_*838的帖子

Rails预览更新关联而不保存到数据库

我希望预览模型在保存时的外观,而不会保存到数据库中.

我正在使用,@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
Run Code Online (Sandbox Code Playgroud)

调节器

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
Run Code Online (Sandbox Code Playgroud)

可能的解决方案?

我想到的可能的解决方案,但不知道该怎么做:

  • 使用某种分配关联的方法,但不会持久化.
  • 为这一个动作禁用所有数据库写入(我不知道该怎么做).
  • 在此操作结束时回滚所有数据库更改

任何有关这些的帮助都会很棒!

更新:
在阅读下面的好答案之后,我最终编写了这个服务类,它将非嵌套属性分配给Event模型,然后在每个嵌套参数上调用collection.build.我做了一点点.很高兴收到意见/建议.

https://gist.github.com/jameskerr/69cedb2f30c95342f64a

ruby activerecord ruby-on-rails ruby-on-rails-4 rails-activerecord

7
推荐指数
1
解决办法
2624
查看次数