I want to preview what the model will look like when saved without currently saving to the database.
I am using @event.attributes =
because that assigns but does not save attributes for @event
to the database.
However, when I also try to assign the audiences
association, Rails inserts new records into the audiences_events
join table. Not cool. Is there a way to preview what these new associations will look like without inserting into the join table?
Model
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
Possible Solutions?
Possible solutions that I thought of, but don't know how to do:
- Using some sort of method that assigns associations, but does not persist them.
- disabling all database writes for this one action (I dont know how to do that).
- Rolling back all database changes at the end of this action
Any help with these would be great!
UPDATE:
After the reading the great answers below, I ended up writing this service class that assigns the non-nested attributes to the Event model, then calls collection.build on each of the nested params. I made a little gist. Happy to receive comments/suggestions.