I want to see what the model will look like when saving without currently saving the database.
I use @event.attributes = because it assigns but does not store the attributes for @event in the database.
However, when I also try to assign an association to audiences , Rails inserts new entries into the audiences_events connection table. Not cool. Is there a way to see how these new associations will look without inserting them into the connection table?
Model
class Event < ActiveRecord::Base has_and_belongs_to_many :audiences
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 about, but don't know how to do this:
- Using some method that assigns associations but is not saved.
- disabling all database entries for this one action (I don't know how to do this).
- Rollback all database changes at the end of this action
Any help with them would be great!
UPDATE:
After reading the wonderful answers below, I wrote this class of service that assigns non-nested attributes to the Event model, and then calls collection.build for each of the nested parameters. I made a little entity. I am pleased to receive comments / suggestions.
https://gist.github.com/jameskerr/69cedb2f30c95342f64a
ruby ruby-on-rails activerecord ruby-on-rails-4 rails-activerecord
jkerr838
source share