我希望预览模型在保存时的外观,而不会保存到数据库中.
我正在使用,@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.我做了一点点.很高兴收到意见/建议.
ruby activerecord ruby-on-rails ruby-on-rails-4 rails-activerecord