Topic: Saving to multiple tables

I have run into a problem...

I have two tables, events and features. They are related by event.rb (has_many :features) and feature.rb (belongs_to :event). I want to be able to set if an event is a feature.

In the form for 'new event', I have a check-box for feature:

<p><label for="feature_event_id">Feature?</label>
<%= check_box 'feature', 'event_id' %></p>

When I save, if checked (true), I want the event_id to go in the feature table, column event_id.

I hope you'll understand...

Re: Saving to multiple tables

The event_id column isn't a boolean field. How does the feature know which event_id to set to? Perhaps what you need is a select field.

<%= collection_select :feature, :event_id, Event.find_all, :id, :name %>

You may need to change :name to some other column in the events table.

Last edited by ryanb (2006-08-04 12:43:26)

Railscasts - Free Ruby on Rails Screencasts

Re: Saving to multiple tables

ryanb wrote:

The event_id column isn't a boolean field. How does the feature know which event_id to set to? Perhaps what you need is a select field.

If the checkbox is checked, when saved, the event_id would be saved to the event_id column in the features table.

In my event_controller.rb, when I save a new event (or update one), can't I put something like this?:

def save
  @event = Event.new(params[:event])
  @feature = Feature.new(params[:feature])
  @feature.save!
  if @event.save     
    flash[:notice] = 'saved!'
    redirect_to :controller => 'frontpage', :action => 'index'
  else
    render :action => 'new'
  end
end

Re: Saving to multiple tables

oh, okay, so you are creating the Event in the same action. You could do something like this:

<%= check_box_tag 'save_event_id', '1', params[:save_event_id] %>

def save
  @event = Event.new(params[:event])
  @feature = Feature.new(params[:feature])
  @feature.event = @event if params[:save_event_id]
  if @event.valid? && @feature.valid? # Don't save them unless both are valid
    @event.save
    @feature.save
    flash[:notice] = 'saved!'
    redirect_to :controller => 'frontpage', :action => 'index'
  else
    render :action => 'new'
  end
end

Completely untested, so you may need to adjust it a little.

Railscasts - Free Ruby on Rails Screencasts

Re: Saving to multiple tables

Yeah, that worked! I don't understand how though...

Re: Saving to multiple tables

Ok, so now I have this:

def save
    @event = Event.new(params[:event])
    if @event.save
      if params[:set_feature]
        f = Feature.new
        f.event_id = @event.id
        f.save
      end
      flash[:notice] = 'Saved!'
      redirect_to :controller => 'frontpage', :action => 'index'
    else
      render :action => 'new'
    end
  end

This saves the new Event.id to the features table if the checkbox is checked, and nothing if it's not.

Thank you ryan for all your help!