ruby-on-rails - Rails 预览更新关联而不保存到数据库

标签 ruby-on-rails ruby ruby-on-rails-4 activerecord rails-activerecord

我想预览保存时模型的外观,但当前未保存到数据库。

我正在使用 @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。我做了一个小要点。很高兴收到评论/建议。

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

最佳答案

在这些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 的一个很好的答案,它解决了一些相同的问题

Rails 3 has_and_belongs_to_many association: how to assign related objects without saving them to the database

关于ruby-on-rails - Rails 预览更新关联而不保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30109549/

相关文章:

ruby-on-rails - 在 rails 4.2 中的 assert_select 中进行转义插值时出错

ruby-on-rails - 使用 Node 或 ruby 读取非常大的 Excel [XLSX] 的最佳方法

ruby-on-rails - 如何实现 twitter-text-rb

ruby - ruby 中的 Set 如何比较元素?

ruby - 确保后台工作人员还活着并在工作

ruby-on-rails - 格式化加密字符串以作为 URL 参数传递

html - Ruby JSON 多词字符串在 HTML 中呈现不正确

ruby-on-rails - 我可以将工厂女孩用于非持久模型吗

ruby - 如何使用带有 Ruby 的 Sinatra gem 隐藏 API key

ruby - rspec 期望通过排除指定的键来比较两个散列